我需要找到一个正则表达式来匹配(全局匹配)字符串中的关键字,并用HTML span标记中包含的关键字替换该关键字的出现次数。但是,如果此关键字出现在http://keyword.com/asdfasdf
之类的网址中(关键字可能出现在网址中的任何位置,而不仅仅是网址中),那么它就不应与之匹配。
这是一个例子。
Keyword = 'yahoo'
原始字符串:
This yahoo that you call http://yahoo.com is nothing but yahoo.
输出字符串:
This <span>yahoo</span> that you call http://yahoo.com is nothing but
<span>yahoo</span>.
如果有帮助,我将在PHP中使用preg_replace
。
答案 0 :(得分:1)
由于PCRE不支持可变长度的后台断言(如(?!=http://\S+)yahoo
),因此最简单的方法是使用回调,例如:
$s = 'This yahoo that you call http://yahoo.com is nothing but yahoo';
echo preg_replace_callback('~((?:htt|ft)ps?://\S+)|yahoo~', function($m) {
return isset($m[1]) ? $m[1] : 'span' . $m[0] . 'span';
}, $s);
// This spanyahoospan that you call http://yahoo.com is nothing but spanyahoospan
答案 1 :(得分:0)
假设你没有“.Yahoo”。除了url.we之外的任何地方都可以有正常的表达式,如
Regex - '(^| )yahoo( |\.|$|!)|(^| \.)yahoo( |$|!)'
以上接受“.yahoo”或“yahoo”。但不是“.yahoo。”
preg_replace中的有一个“i”选项(放在参数1的末尾)也可以用来忽略大小写。
preg_replace("/\b$search\b/i", "<span>$search</span>", $string);