PHP: preg_match? search highlighting

So i’m writing this search feature, that searches out of a database; and it searches fine.

Now what I wanted to do is make it highlight the text, like this:
http://search.atomz.com/search/?sp-q=popular&x=0&y=0&sp-a=sp1002d27b&sp-f=ISO-8859-1&sp-p=All&sp-k=All

A simple way to do it would be to do:


$content = str_replace($search, '<span class="highlight">'.$search.'</span>' , $content);
echo $content;

HOWEVER the problem occurs when $content has markup in it. So say if I do a search for ‘title’ yea, it’ll find anything labeled title just fine. But say content looks like this:


Yea this would be a sample title, for more information go here <a href="#" title="Some silly name">click here</a>

str_replace would then effectively do this:


Yea this would be a sample <span class="highlight">title</span>, for more information go here <a href="#" <span class="highlight">title</span>="Some silly name">click here</a>

notice how it breaks up the anchor tag, booooooo.

SO I was wondering if anyone could show me how I could effectively use some regex method to make the str_replace $content avoid replacing anything that is contained inside of html markup, basically it needs to avoid anything inbetween < and >. if $search is not inbetween < and > apply $x