26: Reverse Text by Grapheme Cluster
Overview
Section titled “Overview”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.
Prerequisites
Section titled “Prerequisites”- PHP 8.6 CLI. Confirm the version with
php --version. - The
intlextension. - Review the previous chapter if you’re following the series in order.
Allow about 10 minutes for the walkthrough and exercise.
What You’ll Build
Section titled “What You’ll Build”A runnable grapheme-strrev.php example.
Step 1: Run the example (~5 min)
Section titled “Step 1: Run the example (~5 min)”Run the following from the root of the Code with PHP repository.
php code/php-8-6/26-grapheme-strrev/grapheme-strrev.php<?php
declare(strict_types=1);
$label = "A:e\u{0301}:👍🏽";echo $label, PHP_EOL;echo grapheme_strrev($label), PHP_EOL;Expected Result
Section titled “Expected Result”A:é:👍🏽👍🏽:é:AWhy It Works
Section titled “Why It Works”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.
Exercise
Section titled “Exercise”Replace the emoji with a two-code-point flag and compare the output before and after reversal. Both regional indicators should stay together.
Wrap-up
Section titled “Wrap-up”Continue with Format Localized Number Ranges.