tags:

views:

36

answers:

2

Hi people

if (preg_match_all ("/\[protected\]\s*(((?!\[protected\]|\[/protected\]).)+)\s*\[/protected\]/g", $text, $matches)) {                                                
        var_dump($matches);
        var_dump($text); 
  }

The text is

<p>SDGDSFGDFGdsgdfog<br>
[protected]<br> STUFFFFFF<br>
[/protected]<br> SDGDSFGDFGdsgdfog</p>

But $matches when var_dump ed (outside the if statement), it gives out NULL

Help people!

A: 
$text= '<p>SDGDSFGDFGdsgdfog<br>
[protected]<br> STUFFFFFF<br>
[/protected]<br> SDGDSFGDFGdsgdfog</p>';

if (preg_match_all ("/\[protected\]\s*(((?!\[protected\]|\[\/protected\]).)+)\s*\[\/protected\]/x", $text, $matches)) {                                                
        var_dump($matches);
        var_dump($text); 
}

There is no g modifier in preg_match - you can read more at Pattern Modifiers . Using x modifier works fine thou.

Nitram Saneco
+2  A: 
  1. You're using / (slash) as the regex delimiter, but you also have unescaped slashes in the regex. Either escape them or (preferably) use a different delimiter.

  2. There's no g modifier in PHP regexes. If you want a global match, you use preg_match_all(); otherwise you use preg_match().

  3. ...but there is an s modifier, and you should be using it. That's what enables . to match newlines.

After changing your regex to this:

'~\[protected\]\s*((?:(?!\[/?protected\]).)+?)\s*\[/protected\]~s'

...I get this output:

array(2) {
  [0]=>
  array(1) {
    [0]=>
    string(42) "[protected]<br> STUFFFFFF<br>
[/protected]"
  }
  [1]=>
  array(1) {
    [0]=>
    string(18) "<br> STUFFFFFF<br>"
  }
}
string(93) "<p>SDGDSFGDFGdsgdfog<br>
[protected]<br> STUFFFFFF<br>
[/protected]<br> SDGDSFGDFGdsgdfog</p>"

Additional changes:

  • I switched to using single-quotes around the regex; double-quotes are subject to $variable interpolation and {embedded code} evaluation.

  • I shortened the lookahead expression by using an optional slash (/?).

  • I switched to using a reluctant plus (+?) so the whitespace following the closing tag doesn't get included in the capture group.

  • I changed the innermost group from capturing to non-capturing; it was only saving the last character in the matched text, which seems pointless.

Alan Moore