gpt4 book ai didi

PHP preg_replace 函数替换以前的匹配项

转载 作者:搜寻专家 更新时间:2023-10-31 20:47:52 25 4
gpt4 key购买 nike

我有一个相当基本的情况,我有一个字符串数组,我想在一个字符串中找到所有匹配项,并在它们周围放置强标签。这是我目前所拥有的:

$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 的编辑:这就像这个或那个或那个字符串。将进行第一场比赛。所以从最长的字符串开始,把最小的字符串作为最后一个。

binary 对此编辑的回答:查看评论


完整版:

<?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);

关于PHP preg_replace 函数替换以前的匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11361943/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com