Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

php - Trying to replace parts of string start with same search chars

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...