【问题标题】:preg_match_all doesn't match properly when caret is used? [closed]使用插入符号时 preg_match_all 不能正确匹配? [关闭]
【发布时间】:2019-02-10 06:27:16
【问题描述】:

其实我正在尝试练习正则表达式修饰符,特别是多行修饰符m,所以写了这个简单的测试字符串:

$subject = "ABC
Some text DEF.
GHI
Some text JKL and some text MNO.
PQR
";

为了在行首只匹配大写的垃圾,所以我写道:

preg_match_all('/^[A-Z][A-Z]+/m',$subject,$m);

但只得到:

array(1) {
 [0]=>
  array(1) {
   [0]=> string(3) "ABC"
  }
}

我也尝试了misU 修饰符,也没有预期的结果:

preg_match_all('/^[A-Z][A-Z]+/misU',$subject,$m);

但是当我在regex101 上测试时,我得到了预期的结果

但奇怪的是,当我复制从 regex101 本身生成的代码时,它也不起作用。

Regex101 中的代码

$re = '/^[A-Z][A-Z]+/m';
$str = 'ABC
Some text DEF.
GHI
Some text JKL and some text MNO.
PQR
    ';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the entire match result
var_dump($matches);

【问题讨论】:

    标签: php regex preg-match-all


    【解决方案1】:

    它不匹配的可能原因是您从正则表达式编辑器复制/粘贴后,代码中出现了前导空格;从字符串中删除前导空格或调整模式。

    $re = '/^\s*[A-Z][A-Z]+/m';
    // this will accommodate leading spaces
    

    否则修复代码(删除前导空格):

    <?php
    
    $re = '/^[A-Z][A-Z]+/m';
    $str = 'ABC
    Some text DEF.
    GHI
    Some text JKL and some text MNO.
    PQR
        ';
    
    preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
    
    // Print the entire match result
    var_dump($matches);
    
    ?>
    

    结果

    array(3) {
      [0]=>
      array(1) {
        [0]=>
        string(3) "ABC"
      }
      [1]=>
      array(1) {
        [0]=>
        string(3) "GHI"
      }
      [2]=>
      array(1) {
        [0]=>
        string(3) "PQR"
      }
    }
    

    【讨论】:

    • 是的,我想当我按回车键时它不会计算自动标签。我的错。谢谢
    猜你喜欢
    • 1970-01-01
    • 2011-09-05
    • 2016-01-23
    • 1970-01-01
    • 2014-04-08
    • 2016-04-03
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多