Skip to content

Instantly share code, notes, and snippets.

@gabrielbarros
Last active March 11, 2024 17:08
Show Gist options
  • Save gabrielbarros/88e720c709a020ad39690a39d1454156 to your computer and use it in GitHub Desktop.
Save gabrielbarros/88e720c709a020ad39690a39d1454156 to your computer and use it in GitHub Desktop.
Reverse a string correctly in PHP considering bytes, code points and graphemes
<?php
// For ASCII only
$hello = 'Hello';
$revStrBytes1 = '';
for ($i = strlen($hello) - 1; $i >= 0; $i--) {
$revStrBytes1 .= $hello[$i];
}
// Alternative to the code above
$revStrBytes2 = strrev($hello);
// For multibyte string, but not combining code points
$cafe = 'Café';
$revStrCodePoints1 = '';
for ($i = mb_strlen($cafe) - 1; $i >= 0; $i--) {
$revStrCodePoints1 .= mb_substr($cafe, $i, 1);
}
// Alternative to the code above
$codePointsCafe = mb_str_split($cafe);
$revStrCodePoints2 = implode('', array_reverse($codePointsCafe));
// For strings that combine code points, like emojis, etc
$flags = '🇧🇷 🇺🇸 🇯🇵';
$revStrGraphemes = '';
for ($i = grapheme_strlen($flags) - 1; $i >= 0; $i--) {
$revStrGraphemes .= grapheme_substr($flags, $i, 1);
}
header('Content-Type: text/plain');
echo "$hello ←→ $revStrBytes1\n";
echo "$hello ←→ $revStrBytes2\n";
echo "$cafe ←→ $revStrCodePoints1\n";
echo "$cafe ←→ $revStrCodePoints2\n";
echo "$flags ←→ $revStrGraphemes\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment