Modern string functions

suggest change

PHP 8.0, 8.3 and 8.4 added string functions that replace common workarounds:

Function Version Replaces
str_contains($haystack, $needle) 8.0 strpos($haystack, $needle) !== false
str_starts_with($haystack, $needle) 8.0 strpos(...) === 0, substr(...) === ...
str_ends_with($haystack, $needle) 8.0 substr($haystack, -strlen($needle)) === $needle
str_increment($string), str_decrement($string) 8.3 $string++ on non-numeric strings ($string-- never worked)
mb_str_pad() 8.3 str_pad(), which pads by bytes
mb_trim(), mb_ltrim(), mb_rtrim() 8.4 trim(), which only knows ASCII whitespace and works with single bytes
mb_ucfirst(), mb_lcfirst() 8.4 ucfirst()/lcfirst(), which only change ASCII letters
grapheme_str_split() 8.4 str_split() / mb_str_split() when you need user-visible characters

The str_* functions are in core and are always available. The mb_* functions need the mbstring extension and the grapheme_* functions need the intl extension. All examples were run with PHP 8.5 with both extensions enabled. In error messages, paths are shortened to /app/.

For the older search functions see Searching a substring with strpos. For what a PHP string is at the byte level see Bytes and binary data and Unicode Support in PHP.

Bytes, code points and graphemes

To pick the right function you need to know which unit it counts in. A PHP string is a sequence of bytes. With UTF-8 text there are three ways to measure it:

<?php
$s = "e\u{301}👍🏽!";   // "e" + combining acute accent, thumbs up + skin tone, "!"
echo $s, "\n";
var_dump(strlen($s));          // bytes
var_dump(mb_strlen($s));       // code points
var_dump(grapheme_strlen($s)); // graphemes (what a user sees as characters)

Output:

é👍🏽!
int(12)
int(5)
int(3)

The user sees 3 characters. They are stored as 5 code points, which take 12 bytes in UTF-8.

str_contains, str_starts_with and str_ends_with

Before PHP 8.0, the usual way to check for a substring was strpos(), and for a prefix or suffix it was strpos() or substr():

<?php
$path = '/admin/users/42';

// before PHP 8.0
var_dump(strpos($path, 'users') !== false);
var_dump(strpos($path, '/admin') === 0);
var_dump(substr($path, -3) === '/42');

// PHP 8.0
var_dump(str_contains($path, 'users'));
var_dump(str_starts_with($path, '/admin'));
var_dump(str_ends_with($path, '/42'));

Output:

bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)

The new functions return a plain bool, which avoids the classic strpos() bug. strpos() returns 0 for a match at the start of the string, and 0 is falsy:

<?php
$s = 'abc';
// the classic bug: strpos() returns 0 for a match at the start
if (strpos($s, 'a')) {
    echo "found with strpos\n";
} else {
    echo "not found with strpos (wrong!)\n";
}
if (str_contains($s, 'a')) {
    echo "found with str_contains\n";
}

Output:

not found with strpos (wrong!)
found with str_contains

str_starts_with($path, '/admin') is also faster than strpos($path, '/admin') === 0 on long strings, because strpos() searches the whole string when the prefix isn't there. str_starts_with() only compares the first bytes.

The empty needle

Every string contains the empty string, so all three functions return true for an empty needle:

<?php
var_dump(str_contains('abc', ''));
var_dump(str_starts_with('abc', ''));
var_dump(str_ends_with('', ''));
var_dump(str_contains('', 'a'));

Output:

bool(true)
bool(true)
bool(true)
bool(false)

This matters when the needle comes from user input. For example, str_contains($title, $search) matches every title when $search is an empty string. Check for an empty search term first.

Case and Unicode

All three functions are case-sensitive and compare bytes. There are no case-insensitive versions. stripos() only folds ASCII letters, so for non-ASCII text lowercase both strings with mb_strtolower() or use mb_stripos():

<?php
$title = 'Ärger im Büro';
var_dump(str_contains($title, 'büro'));
var_dump(stripos($title, 'büro') !== false);
var_dump(stripos($title, 'ärger') !== false);
var_dump(str_contains(mb_strtolower($title), 'ärger'));
var_dump(mb_stripos($title, 'ÄRGER') !== false);

Output:

bool(false)
bool(true)
bool(false)
bool(true)
bool(true)

stripos() finds büro because only the B had to change case. It misses ärger because it doesn't know that Ä and ä are the same letter.

Comparing bytes is safe for UTF-8: a valid UTF-8 needle can't match in the middle of another character. But the same visible text can be stored as different code points. é can be the single code point U+00E9 (NFC form) or e followed by the combining accent U+0301 (NFD form). macOS file names and some input methods produce NFD:

<?php
$nfc = "caf\u{E9}";      // é as one code point
$nfd = "cafe\u{301}";    // e + combining acute accent
echo $nfc, ' ', $nfd, "\n";
var_dump($nfc === $nfd);
var_dump(str_contains($nfd, 'cafe'));   // matches the bytes of "cafe"
var_dump(str_ends_with($nfd, 'é'));     // the 'é' typed in source is NFC

$normalized = Normalizer::normalize($nfd, Normalizer::FORM_C);
var_dump(str_ends_with($normalized, 'é'));

Output:

café café
bool(false)
bool(true)
bool(false)
bool(true)

If text comes from different sources, normalize it with Normalizer::normalize() (intl extension) before comparing.

str_increment and str_decrement

PHP has always allowed ++ on strings. It increments the last letter or digit and carries over, like an odometer: 'a' becomes 'b', 'z' becomes 'aa'. This "Perl-style" increment was a source of surprises, so PHP 8.3 added explicit functions for it:

<?php
foreach (['a', 'z', 'Az', 'zz', 'a9', 'Zz9', '9', '99'] as $s) {
    printf("%-4s -> %s\n", $s, str_increment($s));
}
echo "\n";
foreach (['b', 'aa', 'Ba', 'a0', '10'] as $s) {
    printf("%-4s -> %s\n", $s, str_decrement($s));
}

Output:

a    -> b
z    -> aa
Az   -> Ba
zz   -> aaa
a9   -> b0
Zz9  -> AAa0
9    -> 10
99   -> 100

b    -> a
aa   -> z
Ba   -> Az
a0   -> 9
10   -> 9

Each character keeps its kind: lowercase letters stay lowercase, uppercase stay uppercase and digits stay digits. When the leftmost character carries over, a new character of the same kind is added in front (Zz9 becomes AAa0). str_decrement() is the exact inverse and removes the leading character when it would become a, A or 0.

What was wrong with ++

The ++ operator treats a string differently depending on its content. Numeric strings are converted to numbers, so '1e2' (scientific notation for 100) becomes the float 101. -- doesn't work on non-numeric strings at all. PHP 8.3 started deprecating ++ and -- on non-numeric strings, and as of PHP 8.5 ++ on any non-numeric string emits a deprecation:

<?php
$s = '1e2';
$s++;
var_dump($s);                  // numeric string: becomes a float
var_dump(str_increment('1e2')); // always treated as alphanumeric

$t = 'a-1';
$t++;
var_dump($t);

$u = '';
$u++;
var_dump($u);

$v = 'b';
$v--;
var_dump($v);   // decrement does nothing to non-numeric strings

Output:

float(101)
string(3) "1e3"

Deprecated: Increment on non-numeric string is deprecated, use str_increment() instead in /app/08.php on line 8
string(3) "a-2"

Deprecated: Increment on non-numeric string is deprecated, use str_increment() instead in /app/08.php on line 12
string(1) "1"

Deprecated: Decrement on non-numeric string has no effect and is deprecated in /app/08.php on line 16
string(1) "b"

Use ++ for numbers and str_increment() for alphanumeric strings.

Errors

str_increment() only accepts non-empty strings of ASCII letters and digits. str_decrement() additionally refuses values that have nothing below them. Both throw ValueError instead of producing an odd result:

<?php
foreach (['', 'a-1', 'é', 'a', 'A', '0'] as $s) {
    try {
        echo str_increment($s), "\n";
    } catch (ValueError $e) {
        echo get_class($e), ': ', $e->getMessage(), "\n";
    }
}
foreach (['a', 'A', '0', 'aa'] as $s) {
    try {
        echo "dec: ", str_decrement($s), "\n";
    } catch (ValueError $e) {
        echo get_class($e), ': ', $e->getMessage(), "\n";
    }
}

Output:

ValueError: str_increment(): Argument #1 ($string) must not be empty
ValueError: str_increment(): Argument #1 ($string) must be composed only of alphanumeric ASCII characters
ValueError: str_increment(): Argument #1 ($string) must be composed only of alphanumeric ASCII characters
b
B
1
dec: ValueError: str_decrement(): Argument #1 ($string) "a" is out of decrement range
dec: ValueError: str_decrement(): Argument #1 ($string) "A" is out of decrement range
dec: ValueError: str_decrement(): Argument #1 ($string) "0" is out of decrement range
dec: z

Practical uses

Spreadsheet column names and alphanumeric sequence numbers are where this increment is useful:

<?php
function columnNames(int $count): array
{
    $names = [];
    for ($i = 0, $col = 'A'; $i < $count; $i++, $col = str_increment($col)) {
        $names[] = $col;
    }
    return $names;
}

$cols = columnNames(30);
echo implode(' ', array_slice($cols, 0, 3)), ' ... ', implode(' ', array_slice($cols, -6)), "\n";

$id = 'INV-A0099';
[$prefix, $seq] = explode('-', $id);
echo $prefix, '-', str_increment($seq), "\n";

Output:

A B C ... Y Z AA AB AC AD
INV-A0100

The - in the invoice id isn't allowed, so the code splits it off and increments only the alphanumeric part.

mb_str_pad

str_pad() counts bytes, so text with non-ASCII characters ends up too short and columns don't line up. mb_str_pad() (PHP 8.3) has the same parameters plus an optional encoding, and counts code points:

<?php
$rows = [['Coffee', 3.5], ['Crème brûlée', 6.25], ['Açaí bowl', 8.0]];

echo "str_pad:\n";
foreach ($rows as [$name, $price]) {
    echo '|', str_pad($name, 14), '|', str_pad(number_format($price, 2), 6, ' ', STR_PAD_LEFT), "|\n";
}
echo "mb_str_pad:\n";
foreach ($rows as [$name, $price]) {
    echo '|', mb_str_pad($name, 14), '|', mb_str_pad(number_format($price, 2), 6, ' ', STR_PAD_LEFT), "|\n";
}

Output:

str_pad:
|Coffee        |  3.50|
|Crème brûlée|  6.25|
|Açaí bowl   |  8.00|
mb_str_pad:
|Coffee        |  3.50|
|Crème brûlée  |  6.25|
|Açaí bowl     |  8.00|

Crème brûlée is 12 characters but 15 bytes, so str_pad() thinks it's already wider than 14 and adds nothing.

The pad string can also be multibyte. str_pad() may cut a pad character in half and produce invalid UTF-8:

<?php
var_dump(bin2hex(str_pad('ab', 5, 'é')));  // ends with a lone c3 byte
echo mb_str_pad('ab', 7, 'é'), "\n";
echo mb_str_pad('ab', 7, '·-', STR_PAD_BOTH), "\n";

Output:

string(10) "6162c3a9c3"
abééééé
·-ab·-·

Like str_pad(), mb_str_pad() throws a ValueError if the pad string is empty.

mb_str_pad() counts code points, not screen columns. East Asian characters are usually displayed twice as wide as Latin letters, so they still don't line up in a terminal. For that, measure with mb_strwidth() and pad yourself:

<?php
$names = ['东京', 'Paris'];
foreach ($names as $n) {
    echo '|', mb_str_pad($n, 8), "| width ", mb_strwidth($n), "\n";
}
foreach ($names as $n) {
    echo '|', $n, str_repeat(' ', 8 - mb_strwidth($n)), "|\n";
}

Output:

|东京      | width 4
|Paris   | width 5
|东京    |
|Paris   |

mb_trim, mb_ltrim and mb_rtrim

trim() removes only 6 ASCII bytes by default: space, \t, \n, \r, \0 and \x0B. Text copied from web pages, Word documents or Japanese input methods often contains other whitespace, such as the no-break space U+00A0 or the ideographic space U+3000. mb_trim() (PHP 8.4) knows the Unicode whitespace characters:

<?php
// U+00A0 no-break space, U+3000 ideographic space, U+2003 em space
$input = "\u{00A0}\u{3000} Tokyo \u{2003}";

var_dump(trim($input));
var_dump(mb_trim($input));
var_dump(mb_ltrim($input));
var_dump(mb_rtrim($input));

Output:

string(15) "   Tokyo  "
string(5) "Tokyo"
string(9) "Tokyo  "
string(11) "   Tokyo"

trim() stops at the first non-ASCII byte, so it removes nothing here.

Custom characters

The second argument of trim() is a list of bytes. A multibyte character in that list is split into its bytes, and those bytes are also removed from other characters that share them:

<?php
// trim() takes a list of bytes, so a multibyte character is split into its bytes
$s = 'äpfel ü';
var_dump(trim($s, 'ü'));     // "ü" is C3 BC; the leading "ä" (C3 A4) loses its C3 byte
var_dump(bin2hex(trim($s, 'ü')));
var_dump(mb_trim($s, 'ü'));

var_dump(mb_trim('«quoted»', '«»'));
var_dump(mb_rtrim('Hello!!!…', '!…'));

Output:

string(6) "�pfel "
string(12) "a47066656c20"
string(7) "äpfel "
string(6) "quoted"
string(5) "Hello"

trim() left a lone a4 byte at the start, which is invalid UTF-8. mb_trim() treats the second argument as a list of characters.

When you pass characters, they replace the default list, they don't extend it. A common case is the byte order mark U+FEFF that Excel puts at the start of CSV files. It isn't whitespace, so mb_trim() keeps it by default:

<?php
// a CSV header saved by Excel often starts with a UTF-8 BOM (U+FEFF)
$header = "\u{FEFF}name ";
var_dump(mb_trim($header));                          // BOM is not whitespace
var_dump(mb_trim($header, "\u{FEFF} "));             // characters replace the default list
var_dump(bin2hex(mb_trim($header, "\u{FEFF} ")));

Output:

string(7) "name"
string(4) "name"
string(8) "6e616d65"

One difference from trim(): mb_trim() doesn't support ranges like 'a..z' in the character list. There, . is just another character:

<?php
var_dump(trim('xxhixx', 'a..z'));
var_dump(mb_trim('xxhixx', 'a..z'));
var_dump(mb_trim('...hi...', '.'));

Output:

string(0) ""
string(6) "xxhixx"
string(2) "hi"

mb_ucfirst and mb_lcfirst

ucfirst() and lcfirst() only change the ASCII letters a-z and A-Z. Since PHP 8.2 they also ignore the locale. mb_ucfirst() and mb_lcfirst() (PHP 8.4) work for any script:

<?php
echo mb_str_pad('word', 9), mb_str_pad('ucfirst', 9), mb_str_pad('mb_ucfirst', 12), "mb_lcfirst\n";
foreach (['élan', 'über', 'džungla', 'ßtraße', 'Ärger'] as $w) {
    echo mb_str_pad($w, 9), mb_str_pad(ucfirst($w), 9), mb_str_pad(mb_ucfirst($w), 12), mb_lcfirst($w), "\n";
}

Output:

word     ucfirst  mb_ucfirst  mb_lcfirst
élan     élan     Élan        élan
über     über     Über        über
džungla   džungla   Džungla      džungla
ßtraße   ßtraße   Sstraße     ßtraße
Ärger    Ärger    Ärger       ärger

mb_ucfirst() converts the first character to title case, not uppercase. For most letters they are the same. They differ for digraphs like dž (used in Croatian), whose title case form is Dž and uppercase form is DŽ, and for characters like ß and the ligature fi, which expand to two letters:

<?php
var_dump(mb_ucfirst('dž'), mb_strtoupper('dž'), mb_convert_case('dž', MB_CASE_TITLE));
var_dump(mb_ucfirst('fish'));
var_dump(mb_ucfirst('istanbul'));
var_dump(mb_ucfirst('hELLO wORLD'));
var_dump(mb_convert_case('hELLO wORLD', MB_CASE_TITLE));

Output:

string(2) "Dž"
string(2) "DŽ"
string(2) "Dž"
string(4) "Fish"
string(8) "Istanbul"
string(11) "HELLO wORLD"
string(11) "Hello World"

Two things to keep in mind:

Combined with mb_trim() and the pipe operator (PHP 8.5), this gives a short normalization pipeline:

<?php
function normalizeName(string $raw): string
{
    return $raw
        |> mb_trim(...)
        |> mb_strtolower(...)
        |> mb_ucfirst(...);
}

foreach (["\u{00A0}ŁUKASZ ", "\u{3000}émilie", ' ölçer'] as $raw) {
    var_dump(normalizeName($raw));
}

Output:

string(7) "Łukasz"
string(7) "Émilie"
string(7) "Ölçer"

grapheme_str_split

str_split() splits a string into bytes and mb_str_split() into code points. Neither matches what a user sees as a character. grapheme_str_split() (PHP 8.4, intl extension) splits into grapheme clusters using the Unicode rules from the ICU library:

<?php
$s = "🇵🇱" . "👨\u{200D}👩\u{200D}👧" . "e\u{301}" . "!";   // flag, family, e + accent, "!"

echo count(str_split($s)), " bytes\n";
echo count(mb_str_split($s)), " code points: ";
echo implode(' ', array_map(fn($c) => sprintf('U+%04X', mb_ord($c)), mb_str_split($s))), "\n";
$g = grapheme_str_split($s);
echo count($g), " graphemes:\n";
foreach ($g as $i => $c) {
    echo "  $i: $c (", strlen($c), " bytes)\n";
}

Output:

30 bytes
10 code points: U+1F1F5 U+1F1F1 U+1F468 U+200D U+1F469 U+200D U+1F467 U+0065 U+0301 U+0021
4 graphemes:
  0: 🇵🇱 (8 bytes)
  1: 👨‍👩‍👧 (18 bytes)
  2: é (3 bytes)
  3: ! (1 bytes)

A flag is two "regional indicator" code points. The family emoji is three people joined by zero-width joiners (U+200D). mb_str_split() takes all of them apart.

Reversing a string shows the difference. strrev() reverses bytes and produces invalid UTF-8. mb_str_split() keeps code points intact but moves the accent to the wrong letter and turns the French flag (FR) into the Russian one (RU). Only grapheme_str_split() gets it right:

<?php
$s = "noe\u{308}l 🇫🇷";    // "noël" with a combining diaeresis, then a flag

echo implode('', array_reverse(mb_str_split($s))), "\n";
echo implode('', array_reverse(grapheme_str_split($s))), "\n";

Output:

🇷🇫 l̈eon
🇫🇷 lëon

Like str_split(), it takes an optional chunk length:

<?php
$code = "🇩🇪🇫🇷🇵🇱🇯🇵";
print_r(grapheme_str_split($code, 2));

Output:

Array
(
    [0] => 🇩🇪🇫🇷
    [1] => 🇵🇱🇯🇵
)

A practical use is truncating text for display without cutting a character in half. mb_substr() can split an emoji sequence:

<?php
function truncate(string $s, int $max, string $ellipsis = '…'): string
{
    $chars = grapheme_str_split($s);
    if (count($chars) <= $max) {
        return $s;
    }
    return mb_rtrim(implode('', array_slice($chars, 0, $max - 1))) . $ellipsis;
}

$s = "Party time 👨\u{200D}👩\u{200D}👧 at the café";
echo mb_substr($s, 0, 13), "|\n";   // cuts the family emoji apart
echo truncate($s, 13), "\n";
echo truncate($s, 12), "\n";
echo truncate('short', 13), "\n";

Output:

Party time 👨‍|
Party time 👨‍👩‍👧…
Party time…
short

grapheme_substr() and grapheme_strlen() (available since PHP 5.3) can do the same without building an array. grapheme_str_split() is handier when you need to process each character.

Checking that the extensions are loaded

str_contains(), str_starts_with(), str_ends_with(), str_increment() and str_decrement() are part of core PHP. The others depend on extensions:

Most Linux packages and Docker images enable mbstring. intl is often a separate package (php8.4-intl on Debian/Ubuntu, docker-php-ext-install intl in the official Docker images). On Windows, enable them in php.ini with extension=mbstring and extension=intl. Without the extension the call fails with Error: Call to undefined function mb_trim(). You can check with extension_loaded('mbstring') or php -m.

If you have to support older PHP versions, the Symfony polyfill packages (symfony/polyfill-php80, symfony/polyfill-php83, symfony/polyfill-php84) provide these functions in plain PHP.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents