PHP string functions let you inspect, search, change, split, join, and format text. Common choices include strlen() for byte length, strpos() for finding text, str_replace() for replacement, and explode() for splitting; for human-language text, choose multibyte-aware functions when character encoding matters.
What PHP strings are and how functions handle them
A PHP string is a sequence of bytes. PHP does not attach a universal character encoding to every string, so a function’s behavior depends on what those bytes represent and on the function being used. For plain English text in a UTF-8 application, many familiar functions work as expected, but byte-oriented functions can produce surprising results when text includes accented letters, emoji, or other multibyte characters.
Strings can be written with single or double quotes. Single-quoted strings perform only limited escape processing, while double-quoted strings can interpolate variables and interpret escape sequences such as \n. For example, $name = "Mina"; followed by echo "Hello, $name"; displays “Hello, Mina.” PHP also supports heredoc and nowdoc syntax for longer strings, such as multi-line text, though ordinary quoted strings are sufficient for many tasks.
String functions are built-in PHP functions, so they do not need to be imported. Most return a new value rather than changing the original string in place. Assign the result if you want to keep it: $clean = trim($input); leaves $input unchanged. PHP strings are mutable in some contexts through offset assignment, but treating string-function results as values makes code easier to understand.
Basic string length, extraction, and cleanup
strlen($text) returns the number of bytes in a string, not necessarily the number of visible characters. It is useful for byte-oriented limits and for ordinary ASCII strings. If a UTF-8 string contains multibyte characters, use mb_strlen($text, "UTF-8") to count characters according to that encoding. The Multibyte String extension, commonly called mbstring, must be available for the mb_ functions.
substr($text, $start, $length) extracts part of a string by byte position. For example, with $text = "abcdef";, substr($text, 1, 3) returns bcd. A negative start counts backward from the end. For UTF-8 character positions, consider mb_substr() instead; slicing a multibyte character in the middle with substr() can produce invalid text.
trim($text) removes whitespace from both ends, while ltrim() and rtrim() remove it from the left and right. The optional second argument is a character mask, not a literal phrase to remove. For instance, trim($value, "# ") strips any number signs or spaces at the edges. It does not remove those characters from the middle of the string. This makes trimming useful for cleaning form input, but it is not a substitute for validating the input’s meaning.
Searching for text and checking prefixes
strpos($haystack, $needle) returns the byte position of the first match, or false if there is no match. A match at the beginning returns integer 0, which is false-like in a loose conditional. Check the result with strict comparison: if (strpos($text, "php") !== false) { ... }. This distinguishes “found at position zero” from “not found.”
PHP 8.0 and later provide str_contains($haystack, $needle), which returns a boolean and is often clearer when only presence matters. The same release added str_starts_with() and str_ends_with() for prefix and suffix checks. These functions are case-sensitive. For case-insensitive checks, normalize carefully or use an appropriate multibyte-aware approach if the data can contain non-ASCII letters; simple lowercase conversion is not a complete solution for every language.
For example, a route check could use str_starts_with($path, "/admin/"). That is convenient, but it is not by itself an access-control rule: authorization should check the authenticated user’s permissions rather than trusting a text prefix. For more complex patterns, PHP’s regular-expression functions such as preg_match() can be useful, but regular expressions are harder to maintain than direct string checks for simple cases.
Replacing, changing case, and transforming text
str_replace($search, $replace, $subject) replaces occurrences of one string with another and returns the changed result. For example, str_replace("cat", "dog", $sentence) replaces every matching occurrence in $sentence. The search and replacement arguments can also be arrays, which lets you perform multiple replacements. The optional fourth argument receives the number of replacements made, which can be useful when you need to report whether anything changed.
Functions such as strtolower(), strtoupper(), and ucfirst() handle common case changes, but their behavior is not equivalent to full Unicode case conversion. Use mb_strtolower() or mb_strtoupper() with the intended encoding for multibyte text. Even then, changing case is not always a safe way to compare names or sort words across languages; locale and language-specific rules can matter.
Other transformations include strrev(), which reverses bytes and therefore can break UTF-8 text, and str_pad(), which pads a string to a requested length. Before choosing a transformation, clarify whether the requirement concerns bytes, characters, words, or visual display width. Those are different measurements, particularly for text containing emoji, combining marks, or East Asian characters.
Splitting, joining, and formatting strings
explode($separator, $text) splits a string at a delimiter and returns an array. For example, explode(",", "red,green,blue") produces three values. The separator is exact: splitting a comma-separated line this way does not handle quoted fields containing commas. For real CSV data, use PHP’s CSV functions such as str_getcsv() or file-oriented CSV handling instead of assuming every comma marks a boundary.
implode($separator, $array) joins array elements into one string. Thus, implode(" - ", ["red", "green", "blue"]) produces red - green - blue. It is handy for display labels and constructing simple delimited output. When values may contain the delimiter, choose a format with escaping rules rather than joining raw values and hoping they can later be split correctly.
For controlled output, sprintf() formats values according to a template: sprintf("Item %s costs %.2f", $name, $price) inserts a string and formats a number to two decimal places. Formatting helps keep output structure consistent, but it does not escape values for HTML, SQL, shell commands, or URLs. The correct escaping or parameterization depends on where the string will be used.
Unicode and character encoding choices
UTF-8 is widely used for web text, but PHP’s basic string functions generally operate on bytes. A byte count and a character count can differ: the word café may use more bytes than visible characters in UTF-8, and a single emoji can take several bytes. Consequently, strlen() and substr() are not interchangeable with character-aware operations when processing multilingual input.
Use the mbstring extension’s functions, such as mb_strlen(), mb_substr(), and mb_strtolower(), when the operation is about characters in a known encoding. Specify the encoding when clarity or portability matters. Also ensure that data entering and leaving your application is consistently encoded; a multibyte function cannot repair text that was decoded incorrectly earlier.
Not every display problem is solved by counting Unicode characters. A grapheme cluster can contain multiple code points—for example, a letter and a combining accent—and a displayed symbol may be assembled from several characters. If a user-facing limit must match what people perceive as a single character, investigate grapheme-aware functions such as grapheme_strlen() from the Intl extension. Confirm the relevant extension is installed and enabled in the deployment environment.
Safe output: escaping is context-specific
A common misconception is that a string function called “sanitize” or “escape” can make arbitrary input safe everywhere. Safety depends on the destination. When inserting text into HTML, htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8") is a common way to encode characters that could be interpreted as markup or quotes. It is intended for HTML output, not as a general-purpose defense for SQL, JavaScript, CSS, or shell commands.
For SQL queries, use prepared statements with bound parameters through PDO or MySQLi rather than manually modifying input with str_replace(). For URLs, encode the relevant component with a URL-encoding function, and for JavaScript or other contexts use the escaping strategy designed for that context. Keep the original value for application logic when possible, then encode it at the point where it is rendered or sent.
Validation and escaping solve different problems. Validation decides whether a value is acceptable—for example, whether a quantity is an integer in an allowed range. Escaping represents a value safely in a particular output format. A robust application often needs both, and should not rely on trim() or a blacklist of “dangerous” characters as its security boundary.
Choosing the right function and avoiding common mistakes
Start by defining the operation precisely: find text, compare text, count bytes, count characters, split data, or prepare output. Then choose a function whose return value matches the need. For example, use str_contains() for a yes-or-no presence check on PHP 8 or later, strpos() when the position matters, and mb_strpos() when character positions in multibyte text matter.
- Use strict comparisons for functions that may return
falseor a valid zero value, especiallystrpos(). - Check the PHP version before using newer functions such as
str_contains(),str_starts_with(), orstr_ends_with(); they require PHP 8.0 or later. - Do not use
explode()as a full parser for CSV, JSON, or other formats that have quoting or escaping rules. - Do not assume that “string length” always means visible character count. Identify whether the limit is in bytes, code points, grapheme clusters, or display width.
- Check function documentation for return types and edge cases, and test empty strings, missing delimiters, and non-ASCII input.
For readability, favor a direct built-in function over a complicated regular expression when both solve the same simple task. Conversely, use a parser for structured formats and a regular expression only when a pattern is genuinely needed. The best choice is not the shortest expression; it is the one whose behavior is clear for valid, invalid, and unusual input.
Frequently Asked Questions
What is the most commonly used string function in PHP? There is no single function used most often for every program. strlen(), strpos(), str_replace(), trim(), explode(), and implode() are common because they cover basic length, search, cleanup, replacement, and splitting tasks.
How do I check whether a string contains another string in PHP? In PHP 8.0 or later, use str_contains($text, $search), which returns true or false. On older PHP versions, use strpos($text, $search) !== false; the strict comparison is important because a match at the start has position zero.
Does strlen() count characters or bytes? strlen() counts bytes. For UTF-8 character counts, use mb_strlen($text, "UTF-8") when mbstring is available. If the requirement is based on user-perceived characters, grapheme-aware counting may be more appropriate.
How can I replace part of a string in PHP? Use str_replace($search, $replacement, $text) to replace matching text and store its returned value. If you need to replace text at a particular byte offset, look at substr_replace(); for multibyte text, make sure your chosen method respects character boundaries.
Are PHP string functions safe for user input? The functions themselves do not automatically make input safe. Validate values for your application’s rules, use prepared statements for database queries, and apply context-appropriate encoding such as htmlspecialchars() when outputting text into HTML.
Related
- Microsoft Access Split Form: How It Works and When to Use It
- JavaScript String Split to Array: Examples and Tips
- Balance of Payments: How It Works and What It Shows
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel Transpose Bottom to Top: Formulas and Fixes GuideTo transpose a vertical list from bottom to top into a horizontal row in Excel for Microsoft 365,…
- Excel COUNTIF Contains Date? Formula & ExamplesYes, you can use COUNTIF to count cells that contain a date, but the exact formula depends on…
- How to Capitalize Every Word in Excel with a FormulaTo capitalize every word in Excel, enter =IF(A2="","",PROPER(A2)) in an empty column beside the text in A2, then…
- SUMIF in Excel: Match Cells That Contain Specific TextYes. SUMIF can add values when a cell contains particular text: with descriptions in A2:A7 and amounts in…
- How to Find the Minimum in Excel with the MIN FunctionTo find the smallest number in Excel, use the MIN function. With the numbers you want to check…
- Excel Filter by Text Length: Steps and FormulasTo filter Excel rows by the number of characters in a text cell, add a helper column with…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.