preg_match返回数组中的所有部分

时间:2010-11-03 21:27:21

标签: php regex preg-match

我有以下php代码:

$match = array();
if (preg_match("%^(/\d+)(/test)(/\w+)*$%", "/25/test/t1/t2/t3/t4", $match))
    print_r($match);

我得到了这个结果:

Array ( [0] => /25/test/t1/t2/t3/t4 [1] => /25 [2] => /test [3] => /t4 ) 

我需要在正则表达式中更改以获得此结果:

Array ( [0] => /25/test/t1/t2/t3/t4 [1] => /25 [2] => /test [3] => /t1 [4] => /t2 [5] => /t3  [6] => /t4)

3 个答案:

答案 0 :(得分:0)

你需要preg_match_all

preg_match_all( '~(/\w+)~', $str, $matches );

在您的情况下,您也可以使用爆炸

答案 1 :(得分:0)

<?php

    $str = '/a/b/1/2/3/4';
    if(preg_match('/^(\/\w+)*$/', $str) && preg_match_all('/\/\w+/', $str, $matches)) {
        $matches = $matches[0];
        print_r($matches);
    }

?>

打印:

Array
(
    [0] => /a
    [1] => /b
    [2] => /1
    [3] => /2
    [4] => /3
    [5] => /4
)

答案 2 :(得分:0)

使用原始示例,您可以使用递归表达式:

"%(/\w+)(?>[^(/\w+)]?|(?R))%"

这依次对我的匹配(/ \ w +)子表达式起作用。 <匹配

"/a/b/1/2/3/4"

将是:

Array
(
[0] => Array
    (
        [0] => /a [1] => /b [2] => /1 [3] => /2 [4] => /3 [5] => /4
    )
...

然而,你后面的例子使事情变得复杂。简单的0或更多匹配将仅返回最后一个(贪婪)或第一个(不一致)匹配 - 而不是所有子匹配。 preg_match_all将无法处理您的动态表达式。

在提供合适的解决方案之前,您必须更详细地阐明您想要实现的目标。