2

I need to replace with an X each character every 3rd character

string = "abcdefghijkl" desired output = "abxdexghxjkx"

I tried with this but it replaces every occurrence

$str = "41610236ytm7eszf9d";

//to get the character every 3rd and save in $kept

$kept = preg_replace('/.{2}(.)/', "$1", $concatenated);
$find = str_split($kept);

$replace = array("X","X","X","X","X","X","X");

echo " <br> str_replace <br>"; 
 
echo str_replace($find, $replace, $str);
      echo "<br>";
     echo " <br> str_replace_first <br>"; 
 echo str_replace_first($kept, 'x', $concatenated); 
// outputs : 41X10X3XXtmXesXf9X
gab
  • 23
  • 2

1 Answers1

0

Using preg_replace with this pattern .{2}(.) and replace with $1 will only keep the value of the capture group after the replacement and does not add an x char.

Instead, you could match (.{2}). and replace with $1x

Another option is to match 2 characters, then use \K to forget what is matched and then match a single character, that will be replaced by x

$str = "41610236ytm7eszf9d";
echo  preg_replace('/..\K./', "x", $str);

Output

41x10x36xtmxesxf9x
The fourth bird
  • 154,723
  • 16
  • 55
  • 70