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()andstrtolower()– 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) ormb_strlen()for multibyte strings (e.g., UTF-8). - Finding text: use
strpos()orstrrpos()for last occurrence. For case-insensitive, usestripos(). - Replacing text: use
str_replace()orpreg_replace()for regular expressions. - Extracting a substring: use
substr()ormb_substr()for multibyte. - Comparing strings: use
strcmp()(binary safe, case-sensitive) orstrcasecmp()for case-insensitive. - Formatting output: use
sprintf()orprintf()for formatted strings. - Trimming: use
trim(),ltrim(), orrtrim().
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 useeval()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()beforesubstr()to avoid unnecessary copies. - Build strings with
implode()instead of repeated concatenation in loops. - Use
strtr()for multiple replacements; it’s faster than multiplestr_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
- Train-Test Split: Purpose, Methods, and Common Mistakes
- PostgreSQL: How to Execute a SQL String
- MS Access Split Form: Put the Datasheet on the Bottom
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel COUNTIF Wrong Count? Fixes & CausesIf Excel’s COUNTIF is returning an incorrect count, the cause is almost always one of four things: criteria…
- XLOOKUP Formula: Real Examples in ExcelThe basic XLOOKUP formula is =XLOOKUP(E2,A2:A6,B2:B6): it looks for the value in E2 within A2:A6 and returns the…
- Filter Excel Using a PivotTable: Practical Steps and TipsTo filter Excel data with a PivotTable, click inside the PivotTable, open the PivotTable Fields pane, and drag…
- Excel Conditional Formatting: Create a Formula RuleTo create a formula-based conditional formatting rule in Excel for Microsoft 365 on Windows, select the cells to…
- XLOOKUP Excel Column Match: Find a Column by HeaderTo match a value in an Excel column and return a value from another column, use XLOOKUP with…
- Calculate Age in Excel in Years with Simple FormulasTo calculate completed age in years in Excel, put each birth date in column A and, with the…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.