I'm trying to replace parts of my string. But I met a problem when my search string start with same character:
$string = "Good one :y. Keep going :y2";
$str = str_replace(array_keys($my_array), array_values($my_array), $string);
$my_array= array(":y" => "a", ":y2" => "b");
ouput:
Good one a. Keep going a2
I need my str_replace()
to match the word correctly/exactly.
Besides that you should define your array first before you use it, this should work for you:
Your problem is that
str_replace()
goes through the entire string and replaces everything it can, you can also see this in the manual.And a quote from there:
So for this I used
strtr()
here, because it tries to match the longest byte in the search first.You can also read this in the manual and a quote from there: