How to reverse only the alphabetic characters in a string, keeping other characters in place with PHP

1 Answer

0 votes
function reverse_only_alphabetic_characters(string $s): string {
    $chars = str_split($s);
    $i = 0;
    $j = count($chars) - 1;

    while ($i < $j) {
        if (!ctype_alpha($chars[$i])) {
            $i++;
        } elseif (!ctype_alpha($chars[$j])) {
            $j--;
        } else {
            $tmp = $chars[$i];
            $chars[$i] = $chars[$j];
            $chars[$j] = $tmp;
            $i++;
            $j--;
        }
    }

    return implode('', $chars);
}

$s = "a1-bC2-dEf3-ghIj";

echo $s . PHP_EOL;
echo reverse_only_alphabetic_characters($s) . PHP_EOL;

        
 
/*
run:
             
a1-bC2-dEf3-ghIj
j1-Ih2-gfE3-dCba

*/

 



answered Mar 6 by avibootz
edited Mar 6 by avibootz

Related questions

...