PHP string functions let you inspect, search, split, replace, format, and escape text. A PHP string is a sequence of bytes, so the right function depends not only on the task but also on whether the text is plain ASCII or contains multibyte characters such as accented letters or emoji.
What PHP string functions do
PHP includes many built-in functions for working with strings, alongside the concatenation operator (a period) and language features such as interpolation in double-quoted strings. Together, these tools cover common jobs: checking a value, finding a substring, changing letter case, trimming whitespace, dividing text into pieces, and preparing output.
For example, the period joins strings, while strlen() reports a string’s byte length:
<?php
$name = 'Mina';
$message = 'Hello, ' . $name . '!';
echo $message;
PHP also supports interpolation inside double quotes: "Hello, $name!" produces the same greeting. Single-quoted strings generally treat most characters literally, while double-quoted strings recognize variables and escape sequences such as \n. Use whichever form makes the intended behavior clearest.
String functions usually return a new value rather than changing the original string in place. Assign the returned result if you want to keep a transformation:
$text = ' hello ';
$text = trim($text);
How PHP represents strings
PHP strings are byte sequences and do not carry an inherent text encoding label. In practice, web applications commonly use UTF-8, but PHP does not automatically make every string operation Unicode-aware. A function that counts or slices bytes can therefore produce surprising results when a character uses multiple bytes.
For example, strlen('café') can return 5 when the string is encoded as UTF-8: the final character occupies two bytes, while each of the other three occupies one. The visible text has four characters, but its byte length is five. This distinction matters for character limits, cursor positions, and cutting user-entered text.
Many familiar functions operate on bytes or ASCII characters. For Unicode-aware operations, PHP provides the mb_ family, including mb_strlen(), mb_substr(), and mb_strtolower(). These functions require the Multibyte String extension, which is commonly installed but may need to be enabled in a particular PHP environment. You can specify UTF-8 explicitly, for example mb_strlen($text, 'UTF-8').
Checking length and extracting text
strlen($text) returns the number of bytes, not necessarily the number of human-perceived characters. For UTF-8 text, use mb_strlen($text, 'UTF-8') when you need a character count. Neither count necessarily equals the number of grapheme clusters a person sees: a displayed symbol can be made from multiple Unicode code points. Applications with strict user-visible limits may need more specialized Unicode handling.
substr($text, $offset, $length) extracts part of a string by byte position. Its offset can be negative to count from the end. For example, substr('abcdef', 1, 3) returns bcd, and substr('abcdef', -2) returns ef. Use mb_substr() for character-based slicing of multibyte text.
Other inspection functions answer focused questions. str_word_count() counts words according to its own character rules; it is not a general-purpose linguistic tokenizer for every language. str_contains() checks whether a substring occurs, and str_starts_with() and str_ends_with() check the beginning and end. These three functions require PHP 8.0 or later.
Finding text and interpreting results
strpos($haystack, $needle) returns the numeric position of the first match, or false if no match exists. Positions start at zero, so a match at the first character returns 0. This is a frequent source of bugs: zero is a valid result, and a loose check can mistake it for failure.
$position = strpos($text, 'PHP');
if ($position !== false) {
echo 'Found at byte position ' . $position;
}
Use strict comparison with false when testing whether a match was found. Related functions include strrpos() for the last occurrence, stripos() for a case-insensitive search, and strripos() for the last case-insensitive occurrence. These functions still work with byte positions; they are not full Unicode-aware searches.
For matching patterns rather than literal text, use regular-expression functions such as preg_match() and preg_replace(). Regular expressions are useful for structured checks, but a literal search is clearer and usually simpler with strpos() or str_contains(). A regular expression is not automatically a better choice just because it can search text.
Changing, trimming, and replacing strings
Functions such as strtolower() and strtoupper() change ASCII letter case. For languages with case rules beyond ASCII, use mb_strtolower() or mb_strtoupper() with the intended encoding. Case conversion is not the same as locale-aware sorting or linguistic comparison; those needs call for other tools.
trim($text) removes specified characters from the beginning and end of a string. By default, its character mask includes spaces, tabs, line breaks, null bytes, and vertical tabs. It does not remove a matching phrase: the optional second argument is a set of individual characters. For example, trim($value, 'xyz') removes any of those characters from either edge, not the exact sequence “xyz.” Use ltrim() or rtrim() to trim only the left or right side.
str_replace($search, $replace, $subject) replaces literal text and can accept arrays for multiple replacements. It is case-sensitive; str_ireplace() is case-insensitive. These functions replace occurrences wherever they appear, which is useful for controlled substitutions but not a safe general solution for parsing HTML, SQL, or other structured formats. For regular-expression replacements, use preg_replace() and make sure the pattern expresses the intended boundaries.
Splitting and joining text
explode($separator, $string) divides a string at a literal separator and returns an array. It is handy for simple, predictable formats such as a comma-separated list with no quoted commas. For example, explode(',', 'red,green,blue') returns three values. It does not parse the full CSV format, where quotes can contain separators and line breaks; use PHP’s CSV functions for actual CSV files.
The counterpart, implode($separator, $array), joins array values into a string. For instance, implode(' / ', ['home', 'products', 'books']) returns home / products / books. Validate and normalize the array values before joining if they come from untrusted input or must follow a strict format.
str_split($string, $length) divides text into chunks by byte length, so it can split a multibyte character. For UTF-8 text that must be divided by characters, consider mb_str_split() where available. The right choice depends on whether the task concerns raw bytes, characters, or a defined data format.
Formatting and escaping output
sprintf() builds a formatted string from a template and values; printf() formats and writes the result directly. A format such as 'Item: %s; quantity: %d' uses placeholders for a string and an integer. Formatting is useful for readable messages and predictable numeric display, but it does not validate business rules or make arbitrary data safe for every destination.
Escaping must match the context where text will be used. For HTML text and quoted attribute values, htmlspecialchars() converts characters such as ampersands, angle brackets, and quotes into HTML entities. A typical explicit call is htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'). Use it when rendering untrusted text into an HTML context, and escape at the point of output.
htmlentities() encodes a broader set of characters than htmlspecialchars(), but broader encoding is not automatically safer or necessary. Neither function is a universal sanitizer: JavaScript, CSS, URL, and SQL contexts have different rules. In particular, addslashes() is not a defense against SQL injection. Use parameterized queries with the database extension or library instead of trying to escape SQL values with a string function.
Choosing the right function and avoiding pitfalls
Start by defining the operation and the data’s encoding. Then choose a function whose behavior matches both. A byte-oriented operation can be correct for protocol data or ASCII identifiers, while user-facing UTF-8 text often calls for an mb_ function. Avoid silently mixing assumptions about bytes and characters.
- Use
strpos()for a literal position and compare its result withfalsestrictly. - Use
str_replace()for literal substitutions and regular expressions only when pattern matching is needed. - Use
trim()to remove edge characters, not to delete arbitrary internal whitespace or a whole phrase. - Use
htmlspecialchars()for HTML output, not as a general-purpose input-cleaning function. - Check the PHP version when relying on newer conveniences such as
str_contains(), and check that the mbstring extension is available before usingmb_functions.
Another common misconception is that a function named “string” must understand words or characters as people perceive them. Most core functions do exactly the operation documented, often at the byte level. Reading the function’s return type and edge-case behavior prevents issues such as treating position 0 as false, counting bytes as characters, or assuming replacement handles structured data.
Frequently Asked Questions
What is the difference between strlen() and mb_strlen()?strlen() counts bytes. mb_strlen() counts characters according to a specified multibyte encoding, such as UTF-8. Use the latter when a user-facing character count is needed and the mbstring extension is enabled.
How do I check whether a string contains another string?
On PHP 8.0 and later, use str_contains($text, $search), which returns a Boolean. On older PHP versions, use strpos($text, $search) !== false so a match at position zero is recognized.
Does trim() remove all whitespace from a string?
No. By default, it removes a defined set of characters only from the two ends. It leaves whitespace inside the string untouched. Use another approach, such as a carefully chosen regular expression, if the requirement is to change internal whitespace.
Which PHP function should I use to replace text?
Use str_replace() for literal, case-sensitive replacements and str_ireplace() for literal case-insensitive replacements. Use preg_replace() when the search needs a regular-expression pattern.
Are PHP string functions Unicode-safe?
Not all of them. Many standard functions operate on bytes or ASCII case. The mbstring extension provides Unicode-aware alternatives for common operations, but the encoding still needs to be handled consistently throughout the application.
Related
- What Is a Split Queen Sheet? Size and Fit Explained
- SPLIT_PART in Snowflake: Syntax, Examples, and Tips
- Split Sheet Meaning: What It Is and How It Works
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Split Function in VBScript: Syntax, Examples, and UsesThe Split function in VBScript returns a zero-based, one-dimensional array containing a specified number of substrings, divided from…
- Excel Months Left in Year: Formula & GuideTo calculate the months left in the year from a date in Excel, use the formula =DATEDIF(TODAY(),DATE(YEAR(TODAY()),12,31),"m") —…
- Excel Keep Duplicates: Remove Unique RowsTo keep every row whose value appears more than once, add a helper formula such as =COUNTIF($A$2:$A$8,A2)>1, fill…
- Calculate Age in Excel as of Today: Formulas That WorkTo calculate age in completed years as of today, put each person’s date of birth in A2 and…
- Calculating PMT in Excel: Formula, Payments, and ExamplesTo calculate a fixed periodic loan payment in Excel, use the PMT function, making sure the interest rate…
- Excel SUBTOTAL with FILTER: How to Sum Visible RowsTo total values that remain visible after applying Excel’s built-in column filter, use SUBTOTAL on the original data…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.