捕获括号

时间:2012-11-01 06:31:16

标签: php regex

$url = '/article/math/unit2/chapter3/para4';
$pattern = "\/article";

preg_match_all('/^'.$pattern.'(?:\/([^\/]+))+$/', $url, $matches);

print_r($matches);

输出

Array
(
    [0] => Array
        (
            [0] => /article/math/unit2/chapter3/para4
        )

    [1] => Array
        (
            [0] => para4
        )
)

实际上,我想得到一个如下所示的数组。

Array
(
    [0] => math,
    [1] => unit2,
    [2] => chapter3,
    [3] => para4
)

此代码有什么问题?

UPDATE2:$ pattern是动态模式。可以改为“/ article / foo”,“/ article / foo / bar”等。

7 个答案:

答案 0 :(得分:2)

问题是,对于每个匹配,它会覆盖该匹配的输出

在这种情况下,我认为简单的爆炸比preg_match

更有用

修改:http://php.net/manual/en/function.explode.php

$url = '/article/math/unit2/chapter3/para4';
$args = explode('/', $url);
// since you don't want the first two outputs, heres some cleanup
array_splice($args, 0, 2);

答案 1 :(得分:2)

您可以使用PHP爆炸[参考:http://php.net/manual/en/function.explode.php]

$url = '/article/math/unit2/chapter3/para4';
$data = explode("/", $url);

/是你案件中的分隔符

答案 2 :(得分:2)

使用 explode()

$url = '/article/math/unit2/chapter3/para4';
$arrz = explode("/", $url);
print_r($arrz);

答案 3 :(得分:1)

您只需使用explode()

即可

参考:http://php.net/manual/en/function.explode.php

<?php
    $url = '/article/math/unit2/chapter3/para4';

    $arr = explode("/", str_replace('/article/', '', $url));
    print_r($arr);

?>

以上代码将输出,

Array
(
    [0] => math
    [1] => unit2
    [2] => chapter3
    [3] => para4
)

答案 4 :(得分:1)

也许您应该尝试使用explode()

$url = '/article/math/unit2/chapter3/para4';
$matches = explode('/', $url);
$matches = array_slice($matches, 2); // drop the first 2 elements of the array - "" and "article"

print_r($matches);

答案 5 :(得分:0)

$url = '/article/math/unit2/chapter3/para4';
$url=str_replace('/article/','','/article/math/unit2/chapter3/para4');
print_r(explode('/','/article/math/unit2/chapter3/para4'));

答案 6 :(得分:0)

使用输出中想要的,检查此鳕鱼

<?php

$url = '/article/math/unit2/chapter3/para4';

$newurl = str_replace('/',',',$url);

$myarr = explode(',', $newurl);

$i = 0;
$c = count($myarr);

foreach ($myarr as $key => $val) {
    if ($i++ < $c - 1) {
        $myarr[$key] .= ',';
    }
}
$myarr = array_slice($myarr,2);
print_r($myarr);

<强>输出 -

Array
(
    [0] => math,
    [1] => unit2,
    [2] => chapter3,
    [3] => para4
)