Page 1 of 1

Matching a string once if another preceding match is false

Posted: Tue Jun 10, 2008 1:40 am
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.

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

Posted: Tue Jun 10, 2008 2:49 am
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";
  }
}
?>

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

Posted: Tue Jun 10, 2008 8:31 am
by 0v3rload
That's it. Thanks a lot prometheuzz.

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

Posted: Tue Jun 10, 2008 8:32 am
by prometheuzz
0v3rload wrote:That's it. Thanks a lot prometheuzz.
No problem.