PHP 8.6: New grapheme_strrev function

Version8.6
TypeNew Feature

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.

  • strrev function breaks this Emoji because it operates on individual bytes.
  • There is no mb_strrev function, 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_strrev function correctly reverses grapheme clusters as units, producing AπŸ‘πŸ½C reversed as CπŸ‘πŸ½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 NUL characters, 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_split function added in PHP 8.4. In turn, it is possible to polyfill the grapheme_str_split function 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.


grapheme_strrev RFC Discussion Implementation