开发者

regular expression match word but can NOT be in a url

开发者 https://www.devze.com 2023-02-14 07:13 出处:网络
I need to find a regex to match (global match) a keyword in a string and replace the occurrences of that keyword with keyword wrapped in a HTML span tag. However if this keyword appears in a URL like

I need to find a regex to match (global match) a keyword in a string and replace the occurrences of that keyword with keyword wrapped in a HTML span tag. However if this keyword appears in a URL like http://keyword.com/asdfasdf (the keyword could appear anywhere in the URL, not just the domain) then it should not match that.

Here is an 开发者_如何学编程example.

Keyword = 'yahoo'

Original string:

This yahoo that you call http://yahoo.com is nothing but yahoo.

Output string:

This <span>yahoo</span> that you call http://yahoo.com is nothing but
<span>yahoo</span>.

I will be using preg_replace in PHP if that helps.


Since PCRE doesn't support variable length look-behind assertions (like (?!=http://\S+)yahoo) the simplest method is with a callback, e.g.:

$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


assuming that you will not have ".Yahoo." any where other than in a url.we can have regular expression like

Regex - '(^| )yahoo( |\.|$|!)|(^| \.)yahoo( |$|!)'

The above accepts ".yahoo" or "yahoo." but not ".yahoo."

in preg_replace has an "i" option (which is placed at the end of argument 1) can be used to ignore case as well.

preg_replace("/\b$search\b/i", "<span>$search</span>", $string);
0

精彩评论

暂无评论...
验证码 换一张
取 消