String Functions
Learn the most commonly used built-in PHP functions for measuring, transforming, searching, and splitting strings.
Introduction
Almost every real PHP program spends a lot of its time working with strings: cleaning up user input, formatting text for display, searching for a word inside a sentence, or breaking a comma-separated value into pieces. PHP ships with hundreds of built-in string functions, and a handful of them show up constantly.
This lesson walks through the string functions you will reach for the most: measuring length, changing case, trimming whitespace, replacing text, splitting and joining strings, extracting substrings, and searching inside a string — including the newer, more readable search functions added in PHP 8.
- How to measure and reformat strings with strlen(), strtoupper(), and strtolower().
- How to remove unwanted whitespace with trim(), ltrim(), and rtrim().
- How to find and replace text with str_replace().
- How to split a string into an array (and back) with explode() and implode().
- How to grab part of a string with substr() and locate text with strpos().
- How the PHP 8 functions str_contains(), str_starts_with(), and str_ends_with() simplify common checks.
Measuring Length: strlen()
strlen() returns the number of characters (technically, bytes) in a string. It is one of the most frequently used string functions, often paired with validation logic like "password must be at least 8 characters."
<?php
$name = "PrograMinds";
$empty = "";
echo strlen($name) . "\n";
echo strlen($empty) . "\n";
$password = "secret1";
if (strlen($password) < 8) {
echo "Password is too short.\n";
}
?>12
0
Password is too short.strlen() counts bytes. For plain ASCII text (letters, numbers, common punctuation) that is the same as the character count. For multi-byte text such as emoji or non-Latin scripts, use mb_strlen() instead to count actual characters.
Changing Case
strtoupper() converts a string to all uppercase, and strtolower() converts it to all lowercase. These are useful for case-insensitive comparisons and for formatting display text.
<?php
$city = "New Delhi";
echo strtoupper($city) . "\n";
echo strtolower($city) . "\n";
// Common use: case-insensitive comparison
$input = "YES";
if (strtolower($input) === "yes") {
echo "Confirmed!\n";
}
?>NEW DELHI
new delhi
Confirmed!There are also ucfirst() (capitalizes only the first character) and ucwords() (capitalizes the first letter of every word) for title-style formatting.
<?php
$title = "the great gatsby";
echo ucfirst($title) . "\n";
echo ucwords($title) . "\n";
?>The great gatsby
The Great GatsbyTrimming Whitespace
User input often contains accidental leading or trailing spaces — someone hits the spacebar before typing an email address, or a form field is copy-pasted with extra whitespace. trim() removes whitespace (spaces, tabs, newlines) from both ends of a string; ltrim() removes it only from the left, and rtrim() only from the right.
<?php
$raw = " hello@example.com ";
echo "[" . trim($raw) . "]\n";
echo "[" . ltrim($raw) . "]\n";
echo "[" . rtrim($raw) . "]\n";
?>[hello@example.com]
[hello@example.com ]
[ hello@example.com]By default, trim() removes spaces, tabs, newlines, and a few other whitespace characters. You can pass a second argument to trim off specific characters instead, e.g. trim($text, "/") to remove leading and trailing slashes.
Replacing Text: str_replace()
str_replace() searches a string for one or more values and replaces them with something else. It takes three arguments: what to search for, what to replace it with, and the string (or array of strings) to search inside.
<?php
$sentence = "PHP is fun. PHP is powerful.";
$updated = str_replace("PHP", "JavaScript", $sentence);
echo $updated . "\n";
// Replacing multiple values at once using arrays
$text = "I like cats and dogs.";
$result = str_replace(["cats", "dogs"], ["parrots", "rabbits"], $text);
echo $result . "\n";
?>JavaScript is fun. JavaScript is powerful.
I like parrots and rabbits.str_replace() is case-sensitive, so replacing "php" will not match "PHP". Use the case-insensitive variant str_ireplace() when you need to ignore letter case.
Splitting & Joining Strings
explode() breaks a string into an array of pieces based on a delimiter (a separator character or substring). implode() does the reverse — it joins an array of values back into a single string, placing a chosen separator between each element.
<?php
$csv = "apple,banana,cherry";
$fruits = explode(",", $csv);
print_r($fruits);
echo "First fruit: " . $fruits[0] . "\n";
$joined = implode(" | ", $fruits);
echo $joined . "\n";
?>Array
(
[0] => apple
[1] => banana
[2] => cherry
)
First fruit: apple
apple | banana | cherryexplode() is extremely common for parsing simple delimited data, such as splitting a full name into first and last name, or turning a comma-separated list of tags into an array.
<?php
$fullName = "Ravi Kumar";
$parts = explode(" ", $fullName);
echo "First name: " . $parts[0] . "\n";
echo "Last name: " . $parts[1] . "\n";
?>First name: Ravi
Last name: KumarExtracting Substrings: substr()
substr() extracts a portion of a string, starting at a given position (0-based) for an optional number of characters. It is useful for previews, truncation, and pulling fixed-width fields out of a string.
<?php
$text = "Hello, PrograMinds!";
echo substr($text, 7) . "\n"; // from position 7 to the end
echo substr($text, 7, 12) . "\n"; // 12 characters starting at position 7
echo substr($text, -9) . "\n"; // last 9 characters (negative start)
?>PrograMinds!
PrograMinds
Journey!A negative start position counts backward from the end of the string, which makes it easy to grab "the last N characters" without first calling strlen() to calculate an offset.
Finding Text: strpos()
strpos() searches for the first occurrence of a substring inside a string and returns its numeric position, or false if it is not found. Because 0 is a valid (and falsy-looking) position, strpos() must always be compared using the strict === or !== operators, never == or !=.
<?php
$sentence = "Learning PHP is rewarding.";
$position = strpos($sentence, "PHP");
if ($position !== false) {
echo "Found \"PHP\" at position $position.\n";
} else {
echo "Not found.\n";
}
$missing = strpos($sentence, "Java");
var_dump($missing);
?>Found "PHP" at position 9.
bool(false)if (strpos($sentence, "Learning")) would evaluate to false even though "Learning" is found — because it starts at position 0, and 0 is falsy in a loose boolean check. Always compare the result with !== false or === false.
PHP 8 Search Helpers
PHP 8 introduced three small but very welcome functions that replace common strpos() patterns with clearer, purpose-built alternatives: str_contains(), str_starts_with(), and str_ends_with(). Each returns a plain true or false, so there is no confusing strict-comparison gotcha to remember.
<?php
$email = "amol@example.com";
var_dump(str_contains($email, "@example.com"));
var_dump(str_starts_with($email, "amol"));
var_dump(str_ends_with($email, ".com"));
var_dump(str_contains($email, "yahoo"));
?>bool(true)
bool(true)
bool(true)
bool(false)These functions read almost like plain English, which makes conditional logic involving text much easier to follow than an equivalent strpos() check.
<?php
$filename = "report.pdf";
if (str_ends_with($filename, ".pdf")) {
echo "This is a PDF file.\n";
} else {
echo "Unsupported file type.\n";
}
?>This is a PDF file.str_contains(), str_starts_with(), and str_ends_with() require PHP 8.0 or later. On older PHP versions you would need to combine strpos() with strict comparisons instead.
String Function Reference
Here is a quick-reference table of the string functions covered in this lesson, along with a few closely related ones you will encounter often.
| Function | Description |
|---|---|
| strlen($str) | Returns the number of bytes/characters in a string. |
| strtoupper($str) / strtolower($str) | Converts a string to all uppercase / all lowercase. |
| ucfirst($str) / ucwords($str) | Capitalizes the first letter / the first letter of each word. |
| trim($str) / ltrim($str) / rtrim($str) | Removes whitespace from both ends / left only / right only. |
| str_replace($search, $replace, $str) | Replaces all occurrences of a value (or values) inside a string. |
| explode($delimiter, $str) | Splits a string into an array using a delimiter. |
| implode($separator, $array) | Joins an array of values into a single string. |
| substr($str, $start, $length) | Extracts a portion of a string. |
| strpos($str, $search) | Finds the position of the first occurrence of a substring, or false. |
| str_contains($str, $search) | Checks whether a string contains a substring (PHP 8+). |
| str_starts_with($str, $search) | Checks whether a string starts with a substring (PHP 8+). |
| str_ends_with($str, $search) | Checks whether a string ends with a substring (PHP 8+). |
Common Mistakes
- Comparing strpos() results with == or != instead of === or !== false.
- Forgetting that str_replace() is case-sensitive and expecting it to match differently-cased text.
- Using strlen() on multi-byte (non-ASCII) text and expecting an accurate character count — use mb_strlen() instead.
- Assuming trim() removes characters from the middle of a string — it only trims the two ends.
Best Practices
- Prefer str_contains(), str_starts_with(), and str_ends_with() over strpos() when running on PHP 8+ — they are clearer and avoid the false-comparison pitfall.
- Always trim() user-submitted text before validating or storing it.
- Use explode()/implode() for simple delimited data; reach for regular expressions only when the pattern is more complex.
- Keep the PHP manual's string functions page bookmarked — there are many more specialized functions worth knowing as you go.
Frequently Asked Questions
Why does strpos() return false instead of -1 when nothing is found?
PHP's convention for "not found" in string searches is the boolean false, not a numeric value like -1, since 0 is already a valid position. This is exactly why strict comparison (!== false) is required.
What is the difference between str_replace() and preg_replace()?
str_replace() works with literal text values. preg_replace() uses regular expressions and can match flexible patterns, but is slower and less readable for simple substitutions.
Does explode() ever return fewer elements than expected?
Yes — if the delimiter does not appear in the string at all, explode() returns an array containing the original string as its only element.
Can substr() go past the end of a string?
If the length argument would extend beyond the string, substr() simply returns everything available up to the end rather than throwing an error.
Are str_contains() and similar functions available in older PHP versions?
No, they were introduced in PHP 8.0. Projects targeting PHP 7 need to use strpos() with strict comparisons instead.
Key Takeaways
- strlen() measures string length; strtoupper()/strtolower() change case.
- trim(), ltrim(), and rtrim() remove unwanted whitespace from a string.
- str_replace() finds and replaces text, and is case-sensitive by default.
- explode() splits a string into an array; implode() joins an array back into a string.
- substr() extracts part of a string; strpos() locates a substring and must be compared with !== false.
- PHP 8 added str_contains(), str_starts_with(), and str_ends_with() for clearer, safer text checks.
Summary
String functions are some of the most-used tools in everyday PHP code, whether you are cleaning up form input, formatting text for display, or parsing simple delimited data.
In this lesson, you learned how to measure, transform, search, split, and join strings using PHP's built-in functions, including the newer PHP 8 helpers that make common checks more readable. Next, you will look at how PHP handles numbers.
- You can measure and reformat strings with confidence.
- You know how to trim, replace, split, and join text.
- You understand the strpos() strict-comparison gotcha.
- You can use PHP 8's str_contains() family for cleaner checks.