开发者

php, highlight search keywords without breaking anchor tags

I already did a search on Google and Stackoverflow, but I couldn't find any solution that works for me.

This is what I have so far:

$string = preg_replace('/'.$keyword.'/i', 
'<span class="highlight">$0</span>', $string);

Which works fine, except when the string contains anchor tags. B开发者_开发问答ut I still want to be able to highlight the keywords outside and within the anchor tags.

Example:

$keyword = 's';

Output:

I alrady did a search on Google and Stackoverflow, but I couldn't find any solution that works for me.

I would appreciate it if someone could find a solution for this without having to use PHP Simple HTML DOM Parser.


This should work in most situations:

$string = preg_replace('/(?![^<>]*>)'.preg_quote($keyword,"/").'/i', 
'<span class="highlight">$0</span>', $string);


It seems to me like you'll need to use a DOM parser as you are only wanting to deal with the "text" in your string, rather than the entire string. So you need a way to determine what is "text" and what are HTML attributes.

There are lots of examples of why regex doesn't work for trying to parse HTML.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜