# PHP: preg\_match? search highlighting

**URL:** <https://forum.kirupa.com/t/php-preg-match-search-highlighting/227754>\
**Category:** programming\
**Created:** [June 1, 2007, 7:48pm UTC](https://forum.kirupa.com/t/php-preg-match-search-highlighting/227754 "2007-06-01T19:48:16Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![simplistik](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/simplistik/32/7747_2.png) [@simplistik](https://forum.kirupa.com/u/simplistik)\
**Post date:** [June 1, 2007, 7:48pm UTC](https://forum.kirupa.com/t/php-preg-match-search-highlighting/227754/1 "2007-06-01T19:48:16Z")

</div>

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](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:

```php

$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:

```auto

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:

```auto

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_
