I have a function on my site where the search results have a search query highlighted in the results. However, some of the fields that the site viewed contain HTML. For example, let's say I had a search result consisting of <span>Hello all</span> . If the user was looking for the letter a , I want the code to return <span>Hello <mark>a</mark>all</span> instead of the messy <sp<mark>a</mark>n>Hello <mark>a</mark>ll</sp<mark>a</mark>n> , which he would return now.
I know that I can use negative lookbehinds and lookaheads in preg_replace() to exclude any instances where a is between < and > . But how do I do this? Regular expressions are one of my weaknesses, and I cannot come up with any of this work.
So far I have this:
$return = preg_replace("/(?<!\<[az\s]+?)$match(?!\>[az\s]+?)/i", '<mark>'.$match.'</mark>', $result);
But that does not work. Any help?
source share