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

preg_match_all doesn't match properly when caret is used?

实际上我正在尝试练习正则表达式修饰符,特别是多行修饰符 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 本身生成的代码时,它也不起作用。

Code from 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);

它不匹配的可能原因是在您从正则表达式编辑器 copy/paste 之后,代码中的前导空格结束;从字符串中删除前导空格或调整模式。

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