dongzhang1839 2013-07-17 10:33
浏览 16
已采纳

PHP - preg_match_all相同的组,不同的模式

<?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
    )
  • 写回答

1条回答 默认 最新

  • duanluangua8850 2013-07-17 10:40
    关注

    First of all a regex in PHP needs to be wrapped in boundaries like / or # etc.

    Then your regex doesn't need to be this complex. Same can be simplified using this regex:

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

    Full Code:

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

    OUTPUT:

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

    UPDATE: As per your updated question:

    $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']);
    

    OUTPUT:

    Array
    (
        [0] => img1.png
        [1] => img2.jpg
        [2] => img3.png
        [3] => img4.jpg
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路