0

我有这样的东西

$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] => 
    )

)

所以,问题是为什么我没有' AS `bar`' in $matches[2][0]?(如果我从正则表达式中删除“?”符号,我会得到它,但我需要“?”:))

4

1 回答 1

2

默认情况下,量词+是贪婪的,所以如果第一个可以匹配所有内容,它就会这样做。让它不贪婪应该可以完成这项工作:

preg_match_all('/(`.+?`)(\s+AS\s+`.+`)?/i', '`foo` AS `bar`', $matches);

顺便说一句,$matches = array();这不是必需的 - 变量仅由 by 写入,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`
        )

)
于 2013-05-21T08:09:54.447 回答