尝试以相同的搜索字符替换字符串的一部分 [英] 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");
输出:
Good one a. Keep going a2
我需要我的str_replace()
正确/准确地匹配单词.
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:
$str = strtr($string, $my_array);
您的问题是 str_replace()
贯穿了整个字符串并替换掉所有内容,您也可以在手册中看到它.
Your problem is that str_replace()
goes through the entire string and replaces everything it can, you can also see this in the manual.
并从那里引用:
由于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()
,因为它试图首先匹配搜索中的最长字节.
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:
如果给定两个参数,则第二个参数应为array('from'=>'to',...)形式的数组.返回值是一个字符串,其中所有出现的数组键都已被相应的值替换. 最长的键将首先尝试.替换子字符串后,将不再搜索其新值.
这篇关于尝试以相同的搜索字符替换字符串的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!