尝试用相同的搜索字符替换部分字符串开头

Trying to replace parts of string start with same search chars

我正在尝试替换部分字符串。但是当我的搜索字符串以相同字符开头时我遇到了问题:

$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");

输出:

Good one a. Keep going a2

我需要 str_replace() 来匹配单词 correctly/exactly。

尝试先替换 :y2,然后再替换 :y

$string = "Good one :y. Keep going :y2"; 

$my_array= array(":y2" => "b", ":y" => "a");

$str = str_replace(array_keys($my_array), array_values($my_array), $string);

产出

Good one a. Keep going b

Try it

:y\b

使用此仅替换 :y 而不是 :y2。参见演示。

https://regex101.com/r/sJ9gM7/9

$re = "":y\b"m";
$str = "Good one :y. Keep going :y2\n";
$subst = "a";


$result = preg_replace($re, $subst, $str);

:y2 类似,使用 :y2\b

此外,您应该在使用数组之前先定义它,这应该对您有用:

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

你的问题是 str_replace() 遍历整个字符串并替换它能替换的所有内容,你也可以在手册中看到这一点。

引自那里:

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.

所以为此我在这里使用了 strtr(),因为它首先尝试匹配搜索中最长的字节。

您还可以在手册中阅读此内容并从那里引用:

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.