Core\Str::reverse
Reverses the order of the characters in a string.
Core\Str::reverse takes a string and returns a new string with the last character first and the first character last. The result has the same length as the string you pass in.
A character here is what a person sees as one character. A letter with an accent, an emoji with a skin tone, and a flag are each one character, so they stay whole and in the right order inside. For example, "café" becomes "éfac", not a broken string. The empty string gives the empty string.
Reversing a string twice gives the original string back.
Parameters
$sstringThe string to reverse.
Return value
Returns string. The reversed string. It has the same length as $s. The empty string gives "".
Examples
Reverse a word
<?nvs// Shows how to reverse a word, and that letters with accents stay whole.
// This prints "olleh".echo Core\Str::reverse('hello'), "\n";
// "é" is one character, so it moves as one. This prints "éfac".echo Core\Str::reverse('café'), "\n";
// An emoji with a skin tone is one character too. This prints "🇩🇪 👍🏽 ok".echo Core\Str::reverse('ko 👍🏽 🇩🇪'), "\n";ollehéfac🇩🇪 👍🏽 okFind a palindrome
<?nvs// Shows how to test if a word reads the same from both ends. Such a word is a palindrome.
array<string> $words = ['level', 'Anna', 'rotor', 'novis'];
foreach ($words as string $word) { // `Core\Str::lower` changes "Anna" to "anna", so upper-case letters do not matter. string $plain = Core\Str::lower($word); bool $same = $plain == Core\Str::reverse($plain); // This prints "yes" for the first three words and "no" for "novis". echo $word, ': ', $same ? 'yes' : 'no', "\n";}level: yesAnna: yesrotor: yesnovis: noGroup digits from the right
<?nvs// Shows how to put a space after every three digits of a large number, counted from the right.
array<string> $amounts = ['1250', '987654321', '42'];
foreach ($amounts as string $amount) { // The digits are reversed, so the groups of three start at the left. // `Core\Str::chunk` then splits them into parts of three characters. array<string> $groups = Core\Str::chunk(Core\Str::reverse($amount), 3); // The parts are joined with a space and reversed back. // This prints "1 250", "987 654 321" and "42". echo Core\Str::reverse(Core\Str::join($groups, ' ')), "\n";}1 250987 654 32142