REGEX! Match and bold search terms if not part of "href="

This has to do with searching. When something is found, display the search results, but bold the search terms in the item title and item description.

What shouldn’t happen is that if a searched-for term is part of the anchor “<a href=‘/products/items/platinum/’>” tag, then html code is not inserted around the term in the “href=” as the products page gets compiled and spit out.

Take a search for the word “platinum”.

One item returns a description of “This is a fine platinum item. <a href=‘/items/platinum/1234/’>read more</a>.”

What should get spit out with a preg_replace is:

preg_replace(“match $_POST[‘searchterm’]”, “replace with <b>$searchterm</b>”, “do this to item description”)

The conditions are:

-Only match $_POST[“searchterm”] when “href=” is not located before a space, or an ending “>” to the left of the term.
-Only match $_POST[“searchterm”] when /’ or /" is not found before a space to the right of the term.
-Case insensitive

I created the query correctly in C/C++ regex below:

(href={0})(.[^ ]|.[^>])(searchterm)(?!.[^ ]/\"|.[^ ]/')

Then I tried to insert it into my script, and it didn’t work. Go figure!!

The solution is to remove the parts you don’t want to be replaced, leaving a marker in place so they can later on be put back.
http://web.archive.org/web/20080312155845/http://tagarga.com/blok/on/080307

That’s seriously the best/only way to do this? If the expression can be created in other languages’ regex, I’m surprised that they are more powerful than php/perl’s regex. Regex’s value seemed that its not necessary to create an entirely new function to substitute text in a pattern.

Here are the different flavours of regex that are used across different languages.

Does it help knowing that PHP uses PCRE flavour? I read that:

The PCRE library only supports regex matching, a job it does rather well. It provides no support for search-and-replace, splitting of strings, etc. This is not a major issue, as you can easily do that in your own code.

This is a working expression:

/(?!href=\S*)(searchterm)(?!\S*\/\"|\S*\/\')/i

There may be add’l conditions I need to add in later. This is how it’s being used:

preg_replace(“/(?!href=\S*)(” . $search . “)(?!\S*\/\”|\S*\/\')/i", “<b style=‘color: #ffff00’>$1</b>”, moreLink($descString, $link, 175, true))