使用插入符号时,preg_match_all不正确匹配吗?

时间:2019-02-10 06:27:16

标签: php regex preg-match-all

实际上,我正在尝试练习正则表达式修饰符,特别是多行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上进行测试时,我得到了预期的结果

enter image description here 但是奇怪的是,当我复制从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);

1 个答案:

答案 0 :(得分: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);

?>
相关问题