<?php
$string = 'This is my regular expression';
$array = array();
preg_match('/^.*((my)? regular (expression)?)$/i', $string, $array);
var_dump($array);
?>
执行此脚本后,我有:
array (size=4)
0 => string 'This is my regular expression' (length=29)
1 => string ' regular expression' (length=19)
2 => string '' (length=0)
3 => string 'expression' (length=10)
为什么它不输出捕获组(我的)?
答案 0 :(得分:2)
那是因为你之前有一个贪婪的量词.*
。您应该使用非贪心量词.*?
。
请改为:
<?php
$string = 'This is my regular expression';
$array = array();
preg_match('/^.*?((my)? regular (expression)?)$/i', $string, $array);
var_dump($array);
?>
[OUTPUT]
array (size=4)
0 => string 'This is my regular expression' (length=29)
1 => string 'my regular expression' (length=21)
2 => string 'my' (length=2)
3 => string 'expression' (length=10)