<?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"; }
You have javascript disabled. You will not be able to edit any code.