我有一个相对简单的情况,我有一个字符串数组,我想要在另一个字符串中找到所有匹配项,并在它们周围加上标签。这是我目前的代码:
$searchWords = array("test","this","s");
for($i=0;$i<sizeof($searchWords);$i++) {
$searchWords[$i] = "/".preg_quote($searchWords[$i])."/i";
}
$label = "This is a test string.";
$result = preg_replace($searchWords, "<strong>$0</strong>", $label);
echo($result);
问题在于preg_replace函数似乎将"s"搜索项与标签匹配并替换。所以最后得到的结果是:
<strong>Thisstrong> is a <strong>teststrong>.
而我真正想要的是:
<strong>This</strong> i<strong>s</strong> a <strong>test</strong>.
所以,你们能告诉我问题出在哪里吗?
非常感谢任何帮助,我已经因为这个问题快抓狂了,但我一定很接近解决方法。
array_map
来处理preg_quote
。 - hakrepreg_replace("#s|tests#i", "some tests", '*$0*')
应该返回*s*ome te*s*t*s*
,对吗?因为模式中的第一个字符串是s
而不是tests
。但是,在5.3.14上它返回*s*ome *tests*
。如果我在模式中交换s
和tests
,它也会做同样的事情。 - binaryLVusort()
来对$searchWords
进行排序。@adc124,你也应该在你的代码中包含它。 - binaryLV