"trying to replace parts of string start with same search chars" Answer’s

0

Besides that you should define your array first before you use it, this should work for you:

$str = strtr($string, $my_array);

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:

Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. See also the examples in this document.

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:

If given two arguments, the second should be an array in the form array('from' => 'to', ...). The return value is a string where all the occurrences of the array keys have been replaced by the corresponding values. The longest keys will be tried first. Once a substring has been replaced, its new value will not be searched again.

Wednesday, March 31, 2021
 
mcography
answered 10 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share