2

我有这个子模式:

<?php                                                                                                                                                                                                                                          

    $wavs = 'aaaa="" wav="d" bbbbb="" wav="gerg" ccccc="" wav="" ddddd=""';        
    preg_match_all('#(?<=wav=").+?(?=")#', $wavs, $matches);                    
    print_r($matches);                                                          
?> 

结果是这样的输出:

php test.php 
Array
(
    [0] => Array
        (
            [0] => d
            [1] => gerg
            [2] => " ddddd=
        )

)

虽然我预计只有 2 场比赛:

php test.php 
Array
(
    [0] => Array
        (
            [0] => d
            [1] => gerg
        )

)

这里有什么问题?为什么要捕获额外的不相关字符串?

编辑:(M42响应)

preg_match_all('#(?<=wav=").*?(?=")#', $wavs, $matches);  

仍然导致不正确的匹配:

Array
(
    [0] => Array
        (
            [0] => d
            [1] => gerg
            [2] => 
            [3] => " ddddd=
        )

)

编辑:(嗅探器)

天哪!谢谢你,先生!完全有效!

preg_match_all('#(?<=wav=")\w+?(?=")#', $wavs, $matches);  

Array
(
    [0] => Array
        (
            [0] => d
            [1] => gerg
        )

)
4

3 回答 3

5

这里有什么问题?为什么要捕获额外的不相关字符串?

 #(?<=wav=").+?(?=")#
            ^^^
         This is the reason, it matches everything including the space and the "

你可能想要:

#(?<wav=")\w+(?=")#
于 2013-10-17T15:23:25.347 回答
3

+将修饰符更改为*

preg_match_all('#(?<=wav=").*?(?=")#', $wavs, $matches);   
//                        __^

或者

preg_match_all('#(?<=wav=")[^"]+(?=")#', $wavs, $matches);   
于 2013-10-17T15:22:00.683 回答
3

要解决您可以替换为的问题.+?[^"]+例如:

 preg_match_all('#(?<=wav=")[^"]+(?=")#', $wavs, $matches);
于 2013-10-17T15:23:36.083 回答