Take the 2-minute tour ×

I am looking for a regex to replace a given string in a html page but only if the string is not a part of the tag itself or appearing as text inside a link or a heading.


Looking for 'replace_me'

<p>You can replace_me just fine</p> OK

<a href='replace_me'>replace_me</a> no match

<h3>replace_me</h3> no match

<a href='/test/'><span>replace_me</span></a> no match

<p style="background:url('replace_me')">replace_me<h1>replace_me</h1></p> first no match, second OK, third no match

Thanks in advance!


I have found a working regex

share|improve this question
This would be a pain to do in regex, but: (i) what language? (ii) would you consider using an HTML parser instead? Also, I think this may be within realm of XSLT. –  polygenelubricants Jun 10 '10 at 9:28
Wouldn't a HTML parser use regex-es too? –  Vladimir Jun 10 '10 at 12:17
No, it doesn't. It parses the HTML character by character and stores all relevant parts in a tree-like data structure. –  BalusC Jun 10 '10 at 13:01

2 Answers 2

Parsing HTML with regex is a Bad Idea that will drive you insane. Using regex on this is probably not quite as bad, but a few things to think about in whatever approach you take:

  1. How many of these are there in a page?
  2. How many pages will you be doing this to?
  3. Will you be hand-checking the output, or is it automated?
  4. Which programming language(s) are you using for this?

I think the best way is not with a "simple" (read: horrendously complicated) regex, but a proper program that has some logic behind it - unless regular expressions are Turing Complete and someone else can provide a regex to do what you want, of course :)

share|improve this answer
1. There can be more then one 2 & 3. Automated 4. PHP One of the solutions might be to first replace all links and headings between let's say <noreplace> tags, then perform a regex ignoring content inside these tags? –  Vladimir Jun 10 '10 at 10:06
share|improve this answer

Your Answer


