views:

174

answers:

1

I have a need to perform search and replace operations on large blocks of HTML. I do not wish to change anything that is part of an html tag (like urls) - I also do not wish to change urls OUTSIDE of html tags. I have a partial solution for matching a word that is not inside of html (src):

 word(?!([^<]+)?>)

while regex buddy also says that this will match the same:

 (?!([^<]+)?>)word

so, the only thing left to do is ensure that word is not part of a string that looks like a url - like this:

(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$]

I am unsure if this is possible, my intention is to preserve urls that are present in the text, and are part of the html of the content, while allowing search and replace operations on anything else:

The ideal solution would match DOG and replace with CAT as illustrated below

<h1>DOG</h1> -> <h1>CAT</h1>
<h1 class='DOG'>DOG</h1> -> <h1 class='DOG'>CAT</h1>

<p class='DOG'>DOG: http://www.DOG.com/DOGfood.html DOGfood is delicious.</p> -> <p class='DOG'>CAT: http://www.DOG.com/DOGfood.html CATfood is delicious.</p>

Bonus points for efficiency, I am nearly at my wits end.

A: 

As for matching "DOG" not in a tag: that's how I would do it in general, but I would use this regex instead:

DOG(?![^<>]++>)

[^<>]++ matches one or more of anything that's not an angle bracket possessively. Once it's done, if the next thing isn't '>' it reports failure immediately--no backtracking. You can't get more efficient than that.

However, your idea of using a lookbehind to determine whether you're inside a URL won't work. That would require a variable-length lookbehind match, and PHP doesn't support that--very few regex flavors do.

I recommend an alternation-based approach instead. In a single regex, you match either a complete HTML tag, a complete URL, or your word:

<[^<>]++>
|
(https?|ftp|file)://[A-Z0-9+&@#/%?=~_|$]++(?:[?!:,.;-]++[A-Z0-9+&@#/%=~_|$]++)*+
|
DOG

Use preg_replace_callback to apply the regex, and in the callback you check what it matched. If it's a tag or a URL, plug it back in; if it's "DOG" you replace it with "CAT".

This assumes every angle bracket in the file is part of an HTML tag. If your files may contain SGML comments, you'll have to add an alternative for them, before the one for HTML tags. The same goes for CDATA sections. And of course, attribute values are permitted to contain angle brackets too. That's extremely rare in my experience, but it can be handled too, if necessary.

Alan Moore