preg_match为什么匹配多个空字符串

问题描述 投票:-2回答:2

为什么执行以下正则表达式:

$regex = '^([abc]+)$|^([012]+)$|^([23]+)$|^([123]+)$';
$toMatch = '123';
preg_match('/'.$regex.'/', $toMatch, $matches);

此结果的结果:

array(5) {
  [0]=>
  string(3) "123"
  [1]=>
  string(0) ""
  [2]=>
  string(0) ""
  [3]=>
  string(0) ""
  [4]=>
  string(3) "123"
}

为什么元素1,2和3为空字符串而它们什么都不匹配?为什么会有“空”匹配?

预先感谢

php regex preg-match
2个回答
0
投票

您试图使用()语法捕获4种不同的事物。因此,$matches数组中将有4个不同的元素。仅最后一次捕获将匹配字符串123^[123]+$)。

请参见documentation


0
投票

由于前三个捕获组([abc]+)([012]+)([23]+)不匹配,因此您将收到3个空元素。

如果只需要一个捕获组,则可以这样更新您的正则表达式:

preg_match('/^([abc]+|[012]+|[23]+|[123]+)$/', '123', $match);

哪个会给你:

array(2) {
  [0]=>
  string(3) "123"
  [1]=>
  string(3) "123"
}
© www.soinside.com 2019 - 2024. All rights reserved.