Skip to content

26: Reverse Text by Grapheme Cluster

Reverse a label containing a decomposed accent and an emoji with a skin-tone modifier. A grapheme cluster is a sequence of code points that a user typically sees as one character.

  • PHP 8.6 CLI. Confirm the version with php --version.
  • The intl extension.
  • Review the previous chapter if you’re following the series in order.

Allow about 10 minutes for the walkthrough and exercise.

A runnable grapheme-strrev.php example.

Run the following from the root of the Code with PHP repository.

Terminal window
php code/php-8-6/26-grapheme-strrev/grapheme-strrev.php
grapheme-strrev.php
<?php
declare(strict_types=1);
$label = "A:e\u{0301}:👍🏽";
echo $label, PHP_EOL;
echo grapheme_strrev($label), PHP_EOL;
A:é:👍🏽
👍🏽:é:A

grapheme_strrev() moves whole clusters, preserving the combining accent and modifier with their base characters. This helps with user-visible text encoded in UTF-8.

Replace the emoji with a two-code-point flag and compare the output before and after reversal. Both regional indicators should stay together.

Continue with Format Localized Number Ranges.