How to reverse a string without affecting special characters in PHP

1 Answer

0 votes
function reverseStringWithoutTheSpecialCharacters($str) {
    $right = strlen($str) - 1;
    $left = 0;
    
    while ($left < $right) {
        if (!ctype_alpha($str[$left])) {
                $left++;
        }
        else if (!ctype_alpha($str[$right])) {
                $right--;
        }
        else {
                $tmp = $str[$left];
                $str[$left] = $str[$right];
                $str[$right] = $tmp;
                $left++;
                $right--;
        }
    }
        
    return $str; 
}

$str = "ab*#cde!@$,fg{}";

$str = reverseStringWithoutTheSpecialCharacters($str);
        
echo $str;




/*
run:

gf*#edc!@$,ba{}

*/

 



answered Aug 23, 2022 by avibootz

Related questions

...