String Functions in PHP: W3Schools Guide

Formulas & functions · Updated November 22, 2026

PHP string functions are built-in tools for manipulating text, and W3Schools documents them with examples, syntax, and a full reference list. This article explains the most useful ones, how they work, and how to avoid common mistakes.

What Are PHP String Functions?

PHP provides over 100 built-in functions for working with strings. These functions handle tasks like finding text, replacing parts, changing case, trimming whitespace, splitting, joining, and formatting. They are part of the PHP core, so no installation or special setup is needed. W3Schools lists them alphabetically with a brief description and example for each, making it a quick reference for developers.

Strings in PHP can be defined with single quotes, double quotes, or heredoc/nowdoc syntax. Most string functions work on any of these, but be aware that double-quoted strings interpret escape sequences and variable interpolation, which can affect results.

How String Functions Work: Key Examples

Here are some of the most commonly used PHP string functions, with simple examples:

  • strlen() – returns the length of a string in bytes. Example: strlen("Hello") returns 5.
  • str_replace() – replaces all occurrences of a search string with a replacement. Example: str_replace("world", "PHP", "Hello world") returns “Hello PHP”.
  • strpos() – finds the position of the first occurrence of a substring. Example: strpos("Hello world", "world") returns 6 (0-based).
  • substr() – returns a part of a string. Example: substr("Hello world", 6) returns “world”.
  • strtoupper() and strtolower() – convert a string to uppercase or lowercase. Example: strtoupper("hello") returns “HELLO”.
  • trim() – removes whitespace (or other characters) from the beginning and end of a string. Example: trim(" Hello ") returns “Hello”.
  • explode() – splits a string into an array by a delimiter. Example: explode(",", "apple,banana,cherry") returns ["apple", "banana", "cherry"].
  • implode() – joins array elements into a string. Example: implode("-", ["a", "b", "c"]) returns “a-b-c”.

These functions are case-sensitive by default. For case-insensitive versions, PHP provides str_ireplace(), stripos(), and stristr().

How to Choose the Right Function

Selecting the correct string function depends on what you need to do:

  • Checking length: use strlen() (for bytes) or mb_strlen() for multibyte strings (e.g., UTF-8).
  • Finding text: use strpos() or strrpos() for last occurrence. For case-insensitive, use stripos().
  • Replacing text: use str_replace() or preg_replace() for regular expressions.
  • Extracting a substring: use substr() or mb_substr() for multibyte.
  • Comparing strings: use strcmp() (binary safe, case-sensitive) or strcasecmp() for case-insensitive.
  • Formatting output: use sprintf() or printf() for formatted strings.
  • Trimming: use trim(), ltrim(), or rtrim().

When working with user input, always consider using functions like htmlspecialchars() to prevent XSS attacks, and addslashes() or prepared statements for database queries.

Common Pitfalls and Misconceptions

One common mistake is assuming string positions start at 1. PHP uses 0-based indexing, so strpos("abc", "b") returns 1. Another is forgetting that strpos() returns false when the substring is not found. Because false is loosely equal to 0, always use the strict comparison !== false when checking the result.

Another misconception is that strlen() counts characters. It counts bytes, so for UTF-8 strings with accented characters, it returns more than the character count. Use mb_strlen() for character count.

Also, str_replace() replaces all occurrences by default. If you need to replace only the first occurrence, use preg_replace() with a limit or write a custom function.

Multibyte String Functions

For international text, PHP provides the mbstring extension (usually enabled). Functions like mb_strlen(), mb_substr(), mb_strpos(), and mb_strtolower() handle UTF-8 and other encodings correctly. Without these, functions like substr() can cut a multibyte character in half, producing garbled output.

Example: mb_strlen("café") returns 4, while strlen("café") returns 5 because the é takes two bytes in UTF-8.

To use mbstring functions, ensure the extension is enabled in your PHP installation. Most shared hosts have it on by default.

Security and Best Practices

When using string functions with user input, follow these safety guidelines:

  • Escape output: Use htmlspecialchars() when echoing user input to prevent XSS.
  • Escape database input: Use prepared statements or mysqli_real_escape_string() to prevent SQL injection.
  • Validate input: Use functions like filter_var() for emails, URLs, and numbers.
  • Avoid eval(): Never use eval() with user-supplied strings.

For example, to safely display a user’s name: echo htmlspecialchars($name, ENT_QUOTES, 'UTF-8');.

Performance Considerations

Most string functions are fast, but for large strings or loops, consider the following:

  • Use strpos() before substr() to avoid unnecessary copies.
  • Build strings with implode() instead of repeated concatenation in loops.
  • Use strtr() for multiple replacements; it’s faster than multiple str_replace() calls.
  • For complex pattern matching, regular expressions (preg_*) are powerful but slower than simple string functions.

Micro-optimizations rarely matter unless you’re processing huge amounts of data, but writing clean code with appropriate functions is good practice.

Frequently Asked Questions

What is the difference between strpos() and strstr()? strpos() returns the numeric position of the first occurrence of a substring, while strstr() returns the part of the string starting from the first occurrence (or false if not found). If you only need to check if a substring exists, strpos() !== false is more efficient.

How do I replace only the first occurrence of a string in PHP? Use preg_replace() with a limit: preg_replace('/pattern/', 'replacement', $subject, 1). Or write a custom function using strpos() and substr_replace().

Why does strlen() return more than the number of characters for accented text? Because strlen() counts bytes, not characters. In UTF-8, many characters use multiple bytes. Use mb_strlen() to count characters.

How can I split a string into an array of characters? Use str_split($string) to split into chunks of one character, or preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY) for UTF-8 characters.

Are PHP string functions case-sensitive? Most are, but PHP provides case-insensitive versions like str_ireplace(), stripos(), and strcasecmp(). Check the documentation for each function.

What does sprintf() do? sprintf() formats a string using placeholders like %s for strings and %d for integers. Example: sprintf("Hello %s, you have %d messages", "John", 3) returns “Hello John, you have 3 messages”.

Related

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.