PHP 8.6: New grapheme_strrev function
The Grapheme functions of the Intl extension include a new function named grapheme_strrev, which reverses the order of a string in grapheme units.
The difference from the strrev function is that grapheme_strrev operates on grapheme clusters, while strrev reverses the given string in units of bytes. For ASCII characters, strrev and grapheme_strrev return identical results, but on strings that contain multi-byte or multi code-point characters, grapheme_strrev works correctly because it operates on units of grapheme (smallest functioning unit of a writing system).
For example, consider the Emoji ππ½: It is a combination of the π (U+1F44D) Emoji and the π½ (U+1F3FD) skin tone modifier.
strrevfunction breaks this Emoji because it operates on individual bytes.- There is no
mb_strrevfunction, but even a multibyte-aware reversal would break this structure because the Emoji consists of two multi-byte code points joined:Aππ½C->C π½πA. - Only the
grapheme_strrevfunction correctly reverses grapheme clusters as units, producingAππ½Creversed asCππ½A, for readable text.
New grapheme_strrev function
/**
* Reverse a string by grapheme clusters.
* @param string $string The string to reverse
* @return string|false The reversed string, or false on failure
*/
function grapheme_strrev(string $string): string|false;
- The function is declared in the global namespace.
- The string may contain
NULcharacters, which will also be included in the reversed string.
Usage Examples
grapheme_strrev('ABCDE'); // EDCBA
grapheme_strrev('Appleπ'); // πelppA
grapheme_strrev('π¨π³ - π³π¨'); // π³π¨ - π¨π³
Backward Compatibility Impact
grapheme_strrev is a new function declared in the global namespace. Unless a PHP application declares a function with the same name in the global namespace, this change will not break existing applications.
It is possible to polyfill this function in userland PHP >= 8.4:
function grapheme_strrev(string $string): string|false {
$units = grapheme_str_split($string);
if ($units === false) {
return false;
}
return implode('', array_reverse($units));
}
The polyfill above uses the
grapheme_str_splitfunction added in PHP 8.4. In turn, it is possible to polyfill thegrapheme_str_splitfunction too, using Regexp\X. This requires PCRE >= 10.43, which older PHP versions will likely not include unless otherwise compiled with a custom PCRE version.