3v4l.org

run code in 300+ PHP versions simultaneously
<?php $names = [ 'ab1 ab2', // becomes ba1 ba2 'qwerty uçop', // becomes ytrewq poçu 'q1werty% uio*pl', // becomes y1trewq% lpo*iu 'Привет, мир!', // becomes тевирП, рим! 'Hello, dear @user_non-name, congrats100 points*@!', // olleH, raed @eman_non-resu, stragnoc100 stniop*@! 'a' ]; function swapLetterPositions($string): string { $result = []; foreach (explode(' ', $string) as $index => $word) { $result[$index] = ''; $count = preg_match_all('/(\pL)|(.)/u', $word, $m, PREG_SET_ORDER); for ($i = 0, $j = $count; $i < $count; ++$i) { if (!$m[$i][1]) { // immovable $result[$index] .= $m[$i][2]; // append to string } else { // movable from front while (--$j >= 0) { if ($m[$j][1]) { // movable from back $result[$index] .= $m[$j][1]; // append to string break; } } } } } return implode(' ', $result); } foreach ($names as $name) { echo "\"$name\" => \"" . swapLetterPositions($name) . "\"\n---\n"; }
Output for 7.4.0 - 7.4.33, 8.0.1 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.4, 8.3.6 - 8.3.27, 8.4.1 - 8.4.14
"ab1 ab2" => "ba1 ba2" --- "qwerty uçop" => "ytrewq poçu" --- "q1werty% uio*pl" => "y1trewq% lpo*iu" --- "Привет, мир!" => "тевирП, рим!" --- "Hello, dear @user_non-name, congrats100 points*@!" => "olleH, raed @eman_non-resu, stargnoc100 stniop*@!" --- "a" => "a" ---
Output for 8.3.5
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 "ab1 ab2" => "ba1 ba2" --- "qwerty uçop" => "ytrewq poçu" --- "q1werty% uio*pl" => "y1trewq% lpo*iu" --- "Привет, мир!" => "тевирП, рим!" --- "Hello, dear @user_non-name, congrats100 points*@!" => "olleH, raed @eman_non-resu, stargnoc100 stniop*@!" --- "a" => "a" ---

preferences:
133.59 ms | 409 KiB | 5 Q