Highlight Search Terms

I’m trying to get Search terms from within the Blog’s search engine to be highlighted. I’ve got the following code:

    {if $smarty.request.s == ""}
        {$content}
    {else}
        {assign var=hilite value="<span class='hilite'>"|cat:$smarty.request.s|cat:"</span>"}
        {$content|replace:$smarty.request.s:$hilite}
    {/if}

This works fine, as long as the search term isn’t in a URL, or something like that. In that case, it breaks the URL. To get around this, I need to only replace if it’s not inside an HTML tag. regex_replace to the rescue. This took me about 30 minutes to eventually figure out, a tipoff to wfinn at yakasha dot net, and the comment he made on the PHP documentation pages:

    {if $smarty.request.s == ""}
        {$content}
    {else}
        {assign var=hilite value="<span class='hilite'>"|cat:$smarty.request.s|cat:"</span>"}
        {assign var=regex value="/(?![^< ]*?>)"|cat:$smarty.request.s|cat:"/"}
        {$content|regex_replace:$regex:$hilite}
    {/if}

Obviously, you’ll need to have some sort of CSS styling for the search term.

    .hilite {color:red; border:1px dashed; padding:0 3px; 0 3px;}