The below code should replace all X’s not followed by a 1 with K,
but the it doesn’t work as intended. Can anyone shed some light on what the issue could be? Thanks!
<?php
$test = "XXXX X1 X2 XXX X1";
$test = preg_replace("/X([^1])/", 'K$1', $test);
echo $test;
?>
Input: XXXX X1 X2 XXX X1
Expected output: KKKK X1 K2 KKK X1
Actual output: KXKX X1 K2 KXK X1
Matches cannot overlap. So after finding
XXthe regex engine will continue its search at the third character.Use a negative lookahead instead (which will not be part of the match itself, but only assure that your
Xis not followed by a1):This will also make replacing an
Xat the very end of your string work (which would not have worked before, because[^1]requires that there is actually a character (just not a1).