我需要一个函数,将文本中的特定单词转换为链接,所以我使用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="#">'1</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
如何"告诉"函数不要处理"a"标记之间的单词?
附言:数组中的单词必须随机排序,不要建议我重新排序数组。我需要修改preg_replace
使用查找确保不会替换标签中已经存在的东西,例如
/(?!<a href='"#'".*)'b(".preg_quote($value).")'b(?!.*<'/a>)/i
(?!<a href='"#'".*)
只是通过在搜索词前面添加一个打开标签来检查是否存在(?!.*<'/a>)
确保在您的搜索词之后没有结束标记