PHP preg_replace函数替换先前的匹配项
作者:互联网
我有一个相当基本的情况,我有一个字符串数组,我想在单个字符串中找到所有匹配项,并在它们周围放置强标签.这是我到目前为止的内容:
$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>.
所以,你们能建议我要去哪里错吗?
非常感谢您的帮助,为此我要把头发扯掉,我必须亲近.
解决方法:
您不想进行三项替换,但可以执行一项:
$result = preg_replace("#" . implode($searchWords, "|") . "#", "<strong>$0</strong>", $label);
hakre的编辑:就像这个或那个或那个字符串一样工作.首场比赛将进行.因此,从最长的字符串开始,以最小的字符串作为最后一个.
此编辑的二进制答案:查看评论
完整版本:
<?php
$searchWords = array("t", "test", "this");
usort($searchWords, function ($a, $b) { return strlen($b) - strlen($a); });
foreach ($searchWords as &$word)
{
$word = preg_quote($word);
}
unset($word);
$label = "This is a test string.";
$searchWords = implode($searchWords, "|");
$result = preg_replace("#{$searchWords}#i", "<strong>$0</strong>", $label);
echo($result);
标签:preg-replace,php 来源: https://codeday.me/bug/20191201/2078261.html