我有类似的东西
$matches = array();
preg_match_all('/(`.+`)(\s+AS\s+`.+`)?/i', '`foo` AS `bar`', $matches);
print_r($matches);
结果是
Array
(
[0] => Array
(
[0] => `foo` AS `bar`
)
[1] => Array
(
[0] => `foo` AS `bar`
)
[2] => Array
(
[0] =>
)
)
所以,问题是为什么我$matches[2][0]
中没有'AS`栏'?
(如果我从正则表达式中删除'?'符号,我会得到它,但我需要'?':))
答案 0 :(得分:2)
+
之类的量词在默认情况下是贪婪的,所以如果第一个量词可以匹配它所做的一切。让它不贪婪应该做的工作:
preg_match_all('/(`.+?`)(\s+AS\s+`.+`)?/i', '`foo` AS `bar`', $matches);
顺便说一下,$matches = array();
不是必需的 - 变量只由preg_match_all
写入,因此不需要在之前初始化/定义。
php > preg_match_all('/(`.+?`)(\s+AS\s+`.+`)?/i', '`foo` AS `bar`', $matches);
php > print_r($matches);
Array
(
[0] => Array
(
[0] => `foo` AS `bar`
)
[1] => Array
(
[0] => `foo`
)
[2] => Array
(
[0] => AS `bar`
)
)