1
<?php
    $str = '123.456.789.987,654,321,';

    // preg_match_all('((?<grp1>\d{3})\.|(?<grp2>\d{3})\,)', $str, $matches);
    preg_match_all('((?<grp1>\d{3})\.|(?<grp1>\d{3})\,)', $str, $matches);

    print_r($matches);
?>

Based on code above, I want to get all the string as an group array called grp1, but it always become error PHP Warning: preg_match_all(): Compilation failed: two named subpatterns have the same name at offset .... If I change one of the group name to grp2 it works well.

Is it possible to using 1 group name instead of different group name in preg_match_all?


Update

There is a reason why I cannot using something like this /(?<grp1>\d{3})[.,]/, here is an example to clear the problem:

<?php
    $str = '
        src="img1.png"
        src="img2.jpg"
        url(img3.png)
        url(img4.jpg)
    ';

    preg_match_all('/src=\"(?<img1>(\w+)(.png|.jpg))\"|url\((?<img2>(\w+)(.png|.jpg))\)/', $str, $matches);

    print_r($matches);
?>

I want to take all the img1.png, img2.jpg, img3.png and img4.jpg into array group named img something like this:

[img] => Array
    (
        [0] => img1.png
        [1] => img2.jpg
        [2] => img3.png
        [3] => img4.jpg
    )
4

1 回答 1

1

首先,PHP 中的正则表达式需要包裹在诸如/or之类的边界中#

那么你的正则表达式不需要这么复杂。同样可以使用这个正则表达式来简化:

/(?<grp1>\d{3})[.,]/

完整代码:

$str = '123.456.789.987,654,321,';
preg_match_all('/(?<grp1>\d{3})[.,]/', $str, $matches);
print_r($matches['grp1']);

输出:

Array
(
    [0] => 123
    [1] => 456
    [2] => 789
    [3] => 987
    [4] => 654
    [5] => 321
)

更新:根据您更新的问题:

$str = '
        src="img1.png"
        src="img2.jpg"
        url(img3.png)
        url(img4.jpg)
    ';
preg_match_all('/(?<=src="|url\()(?<img>[^")]+)/i', $str, $matches);
print_r($matches['img']);

输出:

Array
(
    [0] => img1.png
    [1] => img2.jpg
    [2] => img3.png
    [3] => img4.jpg
)
于 2013-07-17T10:40:45.693 回答