php – 尝试用相同的搜索字符替换部分字符串
作者:互联网
我正在尝试更换部分字符串.但是当我的搜索字符串以相同的字符开头时遇到了问题:
$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()来正确/完全匹配单词.
解决方法:
除此之外,您应该在使用之前先定义数组,这应该适合您:
$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.
标签:str-replace,php,regex 来源: https://codeday.me/bug/20190925/1816804.html