Last active
March 11, 2024 17:08
-
-
Save gabrielbarros/88e720c709a020ad39690a39d1454156 to your computer and use it in GitHub Desktop.
Reverse a string correctly in PHP considering bytes, code points and graphemes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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