How to remove a pair of same adjacent characters from string in PHP

1 Answer

0 votes
function removeAdjacentPair(&$s) {
    for ($i = 0; $i < strlen($s) - 1; $i++) {
         if ($s[$i] == $s[$i + 1]) {
             $s = substr_replace($s, '', $i, 2);
             if ($i != 0) $i--;
         }
    }
}

$s = "aabcccdeeffffgac";
 
removeAdjacentPair($s);
         
echo $s;



/*
run:

bcdgac

*/

 



answered Jun 20, 2020 by avibootz
...