PHP预匹配所有正则表达式冲突

PHP预匹配所有正则表达式冲突,php,regex,Php,Regex,正文是 if (preg_match_all ("/\[protected\]\s*(((?!\[protected\]|\[/protected\]).)+)\s*\[/protected\]/g", $text, $matches)) { var_dump($matches); var_dump($text); } SDGDSFGDFGdsgdfog [受保

正文是

if (preg_match_all ("/\[protected\]\s*(((?!\[protected\]|\[/protected\]).)+)\s*\[/protected\]/g", $text, $matches)) {                                                
        var_dump($matches);
        var_dump($text); 
  }
SDGDSFGDFGdsgdfog
[受保护]
填充FFFF
[/protected]
SDGDSFGDFGdsgdfog

但是$matches当
var\u dump
ed(在if语句之外)时,它给出
NULL

救人

$text='SDGDSFGDDSGDFOG
<p>SDGDSFGDFGdsgdfog<br>
[protected]<br> STUFFFFFF<br>
[/protected]<br> SDGDSFGDFGdsgdfog</p>
[受保护]
填充FFFF
[/protected]
SDGDSFGDFGdsgdfog

; 如果(preg\u match\u all(“/\[protected\]\s*((((?!\[protected\]\[\/protected\]))+)\s*\[\/protected\]/x“,$text,$matches)){ var_dump($matches); 变量转储($text); }
preg\u match
中没有
g
修饰符-您可以在上阅读更多内容。使用
x
修饰符效果很好

  • 您正在使用
    /
    (斜杠)作为正则表达式分隔符,但在正则表达式中也有未转换的斜杠。要么转义它们,要么(最好)使用不同的分隔符

  • PHP正则表达式中没有
    g
    修饰符。如果需要全局匹配,可以使用
    preg\u match\u all()
    ;否则使用
    preg\u match()

  • …但是有一个
    s
    修饰符,您应该使用它。这就是使
    能够匹配换行符的原因

  • 将正则表达式更改为以下内容后:

    $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); 
    }
    
    …我得到这个输出:

    '~\[protected\]\s*((?:(?!\[/?protected\]).)+?)\s*\[/protected\]~s'
    
    数组(2){
    [0]=>
    阵列(1){
    [0]=>
    字符串(42)“[受保护]
    填充FFFF
    [/protected]” } [1]=> 阵列(1){ [0]=> 字符串(18)“
    填充FFFF
    ” } } 字符串(93)“SDGDSFGDFGdsgdfog
    [受保护]
    填充FFFF
    [/protected]
    SDGDSFGDFGdsgdfog

    其他更改:

    • 我转而在正则表达式中使用单引号;双引号需要进行
      $variable
      插值和
      {embedded code}
      求值

    • 我使用可选的斜杠(
      /?
      )缩短了前瞻表达式

    • 我改为使用不情愿的加号(
      +?
      ),这样结束标记后面的空格就不会包含在捕获组中

    • 我将最里面的组从捕获更改为非捕获;它只是保存匹配文本中的最后一个字符,这似乎毫无意义

    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>"