仅用 preg_replace() 替换字符串中数组的每个元素一次,而不替换已被替换的文本
Replace every element of an array in a string with preg_replace() only once, without replacing text which already got replaced
我需要一个将文本中的特定单词转换为链接的功能,所以我使用了preg_replace()
。但是,我不知道如何跳过已经转换为链接的单词。
代码如下:
function highlightWords($content)
{
$arr = array("php", "and sql", "sql");
foreach ($arr as $key=>$value)
{
$content = preg_replace("/\b(".preg_quote($value).")\b/i", '<a href="#"></a>', $content, 1);
}
return $content;
}
echo highlightWords("This text will highlight PHP and SQL and sql but not PHPRO or MySQL or sqlite");
该函数应该总共创建 3 个单独的链接 - "php"、"and sql"、"sql"。不幸的是,结果看起来像这样:
This text will highlight <a href="#">PHP</a> <a href="#">and <a href="#">SQL</a></a> and sql but not PHPRO or MySQL or sqlite
如何 "tell" 函数不处理 "a" 标签之间的单词?
P.S。数组中的单词必须随机排序,不建议我重新排序数组。我需要修改 preg_replace
使用环视来确保您不会替换 a 标签中已有的内容,例如
/(?!<a href=\"#\".*)\b(".preg_quote($value).")\b(?!.*<\/a>)/i
(?!<a href=\"#\".*)
只是检查您的搜索字词前面是否有开始标记
(?!.*<\/a>)
确保搜索词后没有结束标记
我需要一个将文本中的特定单词转换为链接的功能,所以我使用了preg_replace()
。但是,我不知道如何跳过已经转换为链接的单词。
代码如下:
function highlightWords($content)
{
$arr = array("php", "and sql", "sql");
foreach ($arr as $key=>$value)
{
$content = preg_replace("/\b(".preg_quote($value).")\b/i", '<a href="#"></a>', $content, 1);
}
return $content;
}
echo highlightWords("This text will highlight PHP and SQL and sql but not PHPRO or MySQL or sqlite");
该函数应该总共创建 3 个单独的链接 - "php"、"and sql"、"sql"。不幸的是,结果看起来像这样:
This text will highlight <a href="#">PHP</a> <a href="#">and <a href="#">SQL</a></a> and sql but not PHPRO or MySQL or sqlite
如何 "tell" 函数不处理 "a" 标签之间的单词?
P.S。数组中的单词必须随机排序,不建议我重新排序数组。我需要修改 preg_replace
使用环视来确保您不会替换 a 标签中已有的内容,例如
/(?!<a href=\"#\".*)\b(".preg_quote($value).")\b(?!.*<\/a>)/i
(?!<a href=\"#\".*)
只是检查您的搜索字词前面是否有开始标记(?!.*<\/a>)
确保搜索词后没有结束标记