tags:

views:

132

answers:

3

I'm trying to write a script that parses a block of HTML and matches words against a given glossary of terms. If it finds a match, it wraps the term in <a class="tooltip"></a> and provides a definition.

It's working okay -- except for two major shortcomings:

  1. It matches text that is in attributes
  2. It matches text that is already in an <a> tag, created a nested link.

Is there any way to have my regular expression match only words that are not in attributes, and not in <a> tags?

Here's the code I'm using, in case it's relevant:

foreach(Glossary::map() as $term => $def) {
  $search[] = "/\b($term)\b/i";
  self::$lookup[strtoupper($term)] = $def;
}

return preg_replace_callback($search, array(&$this,'replace'),$this->content);
+5  A: 

"Don't do that with a regex."

Use an HTML parser, then apply a regex to the contents of HTML elements as it identifies them. That will allow you to easily operate on lots of different variants of HTML structure, valid and otherwise, without a lot of cruft and hard-to-maintain regular expressions.

http://stackoverflow.com/questions/292926

Tim Sylvester
How did you link to another question on StackOverflow regarding this issue and not link to this one: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454?
Jason
How did you like to anything without linking to: http://www.codinghorror.com/blog/archives/001311.html
Ben S
@Jason Because amusing as it may be, it doesn't actually help the OP accomplish anything.
Tim Sylvester
A: 

HTML parsing is an interesting research topic. What do you mean with HTML? There are standards (quite a few), and there are web pages. Most researchers do not use regular expressions to parse HTML

Stephan Eggermont
+3  A: 

Personally, I prefer this answer.

Lee