The string functions in PHP are built-in functions that let you manipulate text, and the most common example is strlen(), which returns the length of a string, like echo strlen("Hello"); which outputs 5. Below you’ll find a practical guide to the most useful string functions, each with a short code example, so you can see exactly how they work in real PHP scripts.
Why String Functions Matter in PHP
PHP is often used to process user input, build web pages, and work with data from databases. Almost all of that data arrives as strings—text from forms, URLs, file contents, or API responses. String functions save you from writing tedious loops to search, replace, cut, and format that text. They are part of the PHP core, so they are always available and require no installation. Understanding them is essential for any PHP developer because they appear in nearly every non-trivial script.
How String Functions Work: The Basics
PHP string functions take one or more strings as arguments and return a new string, a number, or an array. They do not modify the original string because strings in PHP are immutable. For example, strtoupper() returns an uppercase version but leaves the original variable unchanged. Here is a simple example:
$name = "john";
echo strtoupper($name); // outputs JOHN
echo $name; // still john
Most functions are case-sensitive by default. If you need case-insensitive behavior, look for functions with an i in the name, like stristr() or str_ireplace(). Also, remember that PHP string indexes start at 0, so the first character is at position 0.
Essential String Functions with Examples
Here are the most commonly used string functions, grouped by what they do. Each example assumes the variable $text = "Hello World"; unless stated otherwise.
- Length and counting:
strlen($text)returns 11.substr_count($text, "l")returns 3. - Changing case:
strtoupper($text)returns “HELLO WORLD”.strtolower($text)returns “hello world”.ucwords("hello world")returns “Hello World”. - Extracting parts:
substr($text, 0, 5)returns “Hello”.substr($text, -5)returns “World”. - Finding text:
strpos($text, "World")returns 6. If not found, it returnsfalse. - Replacing text:
str_replace("World", "PHP", $text)returns “Hello PHP”. - Trimming:
trim(" Hello ")returns “Hello”.ltrim()andrtrim()remove from the left or right only. - Repeating and padding:
str_repeat("ab", 3)returns “ababab”.str_pad("5", 3, "0", STR_PAD_LEFT)returns “005”. - Exploding and imploding:
explode(",", "a,b,c")returns an array['a','b','c'].implode("-", ['a','b'])returns “a-b”.
Here is a complete example that uses several functions together:
$email = " User@Example.COM ";
$clean = strtolower(trim($email));
echo $clean; // outputs user@example.com
$parts = explode("@", $clean);
echo $parts[0]; // outputs user
How to Choose the Right String Function
With dozens of functions, picking the right one comes down to what you want to do. Ask yourself these questions:
- Do you need to know the length? Use
strlen(). - Do you need to check if a substring exists? Use
strpos()and compare with!== false. - Do you need to replace all occurrences? Use
str_replace(). For case-insensitive, usestr_ireplace(). - Do you need to split a string into an array? Use
explode(). - Do you need to join array elements into a string? Use
implode(). - Do you need to format a number with thousands separators? Use
number_format(), not string functions.
For more complex pattern matching, like validating an email format, use regular expressions with preg_match() instead of multiple string functions.
Common Pitfalls and How to Avoid Them
One of the most common mistakes is assuming strpos() returns true when a substring is found. It actually returns the numeric position, which can be 0 for the first character. Since 0 is falsy in PHP, many beginners write incorrect checks. Always use the strict comparison operator:
if (strpos($text, "Hello") !== false) {
echo "Found";
}
Another pitfall is forgetting that substr() counts from 0, so to get the first character you use substr($text, 0, 1), not substr($text, 1, 1). Also, when using explode(), if the delimiter is not found, it returns an array with the entire string as the only element—not an error. Finally, be careful with multibyte strings (like UTF-8). Functions like strlen() and substr() count bytes, not characters. For UTF-8 text, use the mb_* functions: mb_strlen(), mb_substr(), and mb_strpos().
String Functions vs. Regular Expressions
String functions are faster and simpler for fixed patterns, while regular expressions (regex) are powerful for variable patterns. For example, to check if a string contains a digit, you could loop through characters or use preg_match('/\d/', $text). Regex is also useful for extracting parts of a string, like pulling a phone number from a block of text. However, regex syntax can be complex and harder to read. As a rule, if you can do it with a string function, do that. Use regex only when you need pattern matching that string functions can’t handle.
Performance and Best Practices
String functions are generally fast, but some are slower than others. For example, calling str_replace() in a loop over a large array can be slow; consider using strtr() for multiple replacements at once. Also, avoid unnecessary string concatenation in loops; use an array and implode() at the end. When building large strings, use the . operator or sprintf() for readability. Always validate user input before using it in string functions to avoid unexpected behavior, especially with functions like eval() (which you should never use on user input).
Frequently Asked Questions
How do I get the first character of a string in PHP?
Use substr($string, 0, 1) to get the first character. For the last character, use substr($string, -1). Remember that this works on bytes, so for UTF-8 characters use mb_substr($string, 0, 1).
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. For example, strstr("Hello World", "World") returns “World”, not the position. Use strpos() when you need the index, and strstr() when you need the remainder of the string.
How can I replace all spaces with underscores in PHP?
Use str_replace(' ', '_', $string). This replaces every space with an underscore. If you want to replace multiple whitespace characters (like tabs), use a regex: preg_replace('/\s+/', '_', $string).
Why does strlen return the wrong length for accented characters?
Because strlen() counts bytes, and accented characters in UTF-8 take two bytes. For example, strlen("é") returns 2. Use mb_strlen($string, 'UTF-8') to get the correct character count.
How do I check if a string starts with a specific word in PHP?
Use strpos($string, $word) === 0 to check if the word is at the beginning. Alternatively, use strncmp($string, $word, strlen($word)) === 0 for a case-sensitive check. For case-insensitive, use stripos() or strncasecmp().
Is there a function to reverse a string in PHP?
Yes, strrev($string) reverses a string. For example, strrev("Hello") returns “olleH”. This works on bytes, so for UTF-8 text with multibyte characters, it may produce invalid output; use mb_strrev() if you need proper character reversal.
Related
- Shortcut Keys Save As: The Full Guide
- Is SELECT a Clause in SQL? Yes, Here’s Why
- US Balance of Trade Data: Latest Figures & Trends
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Combine Cells in Excel Without Merging: Formulas and StepsTo combine the contents of cells without merging them, put the result in a separate cell with a…
- Excel Text Join With Line Breaks: Formulas and TipsTo join text with a line break in Excel for Microsoft 365, use TEXTJOIN with CHAR(10) as the…
- Excel Filter Shortcut: Turn AutoFilter On or OffIn Excel for Microsoft 365 on Windows, press Ctrl+Shift+L to turn the filter buttons on or off. The…
- How to Get Out of Filter Mode in Excel and Show All RowsTo get out of filter mode in Excel and show every row, select a cell in the filtered…
- Excel INDEX MATCH Tutorial: Exact and Flexible LookupsTo look up a value with INDEX MATCH in Excel, use MATCH to find the position of a…
- Excel COLUMN Function: Return a Column Letter from a NumberExcel’s COLUMN function returns a column number, not a letter. To display a column letter, combine it with…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.