PHP String Functions
PHP ships with well over a hundred built-in string functions. You don't need to memorise them all — a dozen or so cover nearly every real-world task: measuring, searching, changing case, trimming, replacing, splitting and formatting.
Length, case and whitespace
<?php
$raw = " Hello, PHP World! ";
echo "[" . trim($raw) . "]\n";
echo "[" . ltrim($raw) . "]\n";
echo "[" . rtrim($raw) . "]\n";
$text = trim($raw);
echo strlen($text), "\n";
echo strtoupper($text), "\n";
echo strtolower($text), "\n";
echo ucfirst("banana split"), "\n";
echo ucwords("the quick brown fox"), "\n";[Hello, PHP World!]
[Hello, PHP World! ]
[ Hello, PHP World!]
17
HELLO, PHP WORLD!
hello, php world!
Banana split
The Quick Brown Fox
trim() removes spaces, tabs and newlines from both ends — almost always the first thing you do with user input.
Searching inside a string
| Function | Returns |
|---|---|
str_contains($h, $n) |
true/false (PHP 8+) |
str_starts_with($h, $n) / str_ends_with($h, $n) |
true/false (PHP 8+) |
strpos($h, $n) |
position of the first match, or false |
stripos($h, $n) |
same, case-insensitive |
substr_count($h, $n) |
how many times $n occurs |
<?php
$email = "support@tadmarket.example";
var_dump(str_contains($email, "@"));
var_dump(str_starts_with($email, "support"));
var_dump(str_ends_with($email, ".com"));
echo strpos($email, "@"), "\n";
echo substr_count("banana", "a"), "\n";
$pos = strpos("hello", "z");
if ($pos === false) {
echo "'z' not found\n";
}bool(true)
bool(true)
bool(false)
7
3
'z' not found
Tip: Always compare the result of
strpos()with=== false. If the match is at position0, a looseif (!$pos)check would wrongly treat it as "not found".
Extracting and replacing
substr($s, $start, $length) cuts out a piece; negative values count from the end. str_replace() swaps every occurrence of one text for another and can take arrays for several replacements at once.
<?php
$code = "INV-2025-00042";
echo substr($code, 0, 3), "\n"; // first 3 characters
echo substr($code, 4, 4), "\n"; // year
echo substr($code, -5), "\n"; // last 5 characters
echo str_replace("-", "/", $code), "\n";
$template = "Dear {name}, your order {id} has shipped.";
echo str_replace(["{name}", "{id}"], ["Khoa", "#118"], $template), "\n";
echo strrev("stressed"), "\n";
echo str_repeat("=-", 5), "\n";
echo str_pad("7", 3, "0", STR_PAD_LEFT), "\n";INV
2025
00042
INV/2025/00042
Dear Khoa, your order #118 has shipped.
desserts
=-=-=-=-=-
007
Splitting and joining
explode() turns a string into an array using a separator; implode() does the reverse. These two functions are how PHP reads simple CSV lines, tag lists and paths.
<?php
$line = "apple,banana,cherry";
$fruits = explode(",", $line);
echo count($fruits), " fruits\n";
echo $fruits[1], "\n";
echo implode(" | ", $fruits), "\n";
$words = str_word_count("PHP makes web pages dynamic");
echo "$words words\n";
print_r(str_split("ABCDEF", 2));3 fruits
banana
apple | banana | cherry
5 words
Array
(
[0] => AB
[1] => CD
[2] => EF
)
Formatting with sprintf and number_format
sprintf() builds a string from a pattern with placeholders, much like printf in C. printf() does the same but prints immediately.
| Placeholder | Meaning | Example result |
|---|---|---|
%s |
string | Ann |
%d |
integer | 42 |
%.2f |
float with 2 decimals | 3.14 |
%5d |
integer padded to width 5 | 42 |
%-8s |
left-aligned string, width 8 | Ann |
%05.1f |
zero-padded float | 003.5 |
<?php
$items = [["Tea", 2, 3.5], ["Cake", 1, 4.25], ["Water", 3, 0.9]];
foreach ($items as [$name, $qty, $price]) {
printf("%-6s x%d %6.2f\n", $name, $qty, $qty * $price);
}
$label = sprintf("Order #%05d", 42);
echo $label, "\n";
echo number_format(1234567.891), "\n";
echo number_format(1234567.891, 2), "\n";
echo number_format(1234567.891, 2, ",", "."), "\n";Tea x2 7.00
Cake x1 4.25
Water x3 2.70
Order #00042
1,234,568
1,234,567.89
1.234.567,89
Note: Most of these functions work on bytes. For UTF-8 text with non-English letters, use the
mb_variants:mb_strlen(),mb_substr(),mb_strtoupper().
Test yourself
What does strpos("hello", "h") return?
true10false
Which function splits "a;b;c" into an array?
implode(";", $s)explode(";", $s)str_split($s, ";")substr($s, ";")
What does sprintf("%04d", 7) produce?
7700000077