0

I have problems constructing a reg exp. I think I should use lookahead/behind but I just don't make it.

I want to make a reg-exp that catches all HTML tags that do NOT contain a string ('rabbit').

For example, the following tags should be matched

<a XXX> <span yyy> </div x zz> </li qwerty=ab cd> <div hello=stackoverflow>

But not the following

<a XXrabbitX> <span yyyrabbit> </div xrabbitzz> </li rabbit=abcd hippo=9876> <div hello=rabbit>

(My next step is to make make a substitution so that the word rabbit enters the tags, but that will hopefully come easy.)

(I use PHP5-preg_replace.)

Thanks.

cvr
  • 161
  • 1
  • 2
  • 10
  • possible duplicate of [RegEx match open tags except XHTML self-contained tags](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – Daniel DiPaolo Mar 20 '11 at 02:34

1 Answers1

0

I guess you're matching the HTML tags with a regex something like this:

/<[^>]*>/

You can add a negative look-ahead assertion in there to assert that "rabbit" cannot be found in the tag:

/<(?![^>]*rabbit)[^>]*>/
Anomie
  • 92,546
  • 13
  • 126
  • 145
  • Thank you. However, it doesn't work for me. After matching a string, also the tags that should NOT match are gone. I am sorry, I am trying to include the example, but I haven't mastered the editor in stack overflow. $string = "
    "; $pattern = "/<(?![^>]*rabbit)[^>]*>/"; echo preg_replace($pattern, "[MATCH]", $string);
    Output [MATCH] [MATCH] [MATCH] [MATCH] [MATCH]
    – cvr Mar 20 '11 at 02:45
  • I copy-and-pasted your example and it works for me, on both php 5.2.6 and php 5.3.5. – Anomie Mar 20 '11 at 03:13
  • So you get the following output? `[MATCH] [MATCH] [MATCH] [MATCH] [MATCH]
    ` I just get five [MATCH] and nothing more. I use PHP Version 5.2.17
    – cvr Mar 20 '11 at 03:43
  • I apologize, my error, it works for me now, thread solved. Thanks Anomie – cvr Mar 20 '11 at 03:52
  • Anomie's regex works perfectly here, too. Please post the code you are using to apply this regex. – ridgerunner Mar 20 '11 at 03:56
  • Like I just wrote it is my mistake, I applied the example wrongly. (I thught I was looking at text output but it was HTML.) Anomie's reply is fine, thanks. Thread solved. – cvr Mar 20 '11 at 03:59