Matching a string once if another preceding match is false

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
0v3rload
Forum Newbie
Posts: 4
Joined: Tue May 01, 2007 3:14 am

Matching a string once if another preceding match is false

Post by 0v3rload »

Hello,

I need to match a specific string of chars against a chunk of HTML code. As an example let's say this chunk of HTML code is:

Code: Select all

<tr><td class="nbr"><span [b]class="c2"[/b]>•</span>&nbsp; <a href="http://server.com?id=1234" [b]class="c2"[/b]>Caption goes here</a></td><td class="right">
. . .

I need a RegEx expression that matches class="c2" only once (first match) and only if there aren't any closing HTML tags before it. So the match would be successful if ran against the HTML code given above but would be unsuccessful against:

Code: Select all

<tr><td class="nbr"><tag>[b]</tag>[/b]<span [b]class="c2"[/b]>•</span>&nbsp; <a href="http://server.com?id=1234" [b]class="c2"[/b]>Caption goes here</a></td><td class="right">
. . .

I would appreciate some help as I seem to not be able to understand the way this whole RegEx thing works and that's deeply frustrating.
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: Matching a string once if another preceding match is false

Post by prometheuzz »

Something like this?

Code: Select all

<?php
$tests = array(
  '<tr><td class="nbr"><span class="c2">•</span>&nbsp; <a href="http://server.com?id=1234" class="c2">Caption goes here</a></td><td class="right">',
  '<tr><td class="nbr"><tag></tag><span class="c2">•</span>&nbsp; <a href="http://server.com?id=1234" class="c2">Caption goes here</a></td><td class="right">'
);
foreach($tests as $t) {
  if(preg_match('#^(?:.(?!</[^>]++>))+?class="c2"#', $t)) {
    echo "match!\n";
  } else {
    echo "no match\n";
  }
}
?>
0v3rload
Forum Newbie
Posts: 4
Joined: Tue May 01, 2007 3:14 am

Re: Matching a string once if another preceding match is false

Post by 0v3rload »

That's it. Thanks a lot prometheuzz.
User avatar
prometheuzz
Forum Regular
Posts: 779
Joined: Fri Apr 04, 2008 5:51 am

Re: Matching a string once if another preceding match is false

Post by prometheuzz »

0v3rload wrote:That's it. Thanks a lot prometheuzz.
No problem.
Post Reply