0
$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”等。

4

7 回答 7

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);
于 2012-11-01T06:34:00.153 回答
2

你可以使用 PHP Explode [参考: http: //php.net/manual/en/function.explode.php ]

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

/ 在您的情况下是分隔符

于 2012-11-01T06:36:31.650 回答
2

使用explode()

$url = '/article/math/unit2/chapter3/para4';
$arrz = explode("/", $url);
print_r($arrz);
于 2012-11-01T06:38:03.113 回答
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
)
于 2012-11-01T06:36:46.410 回答
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);
于 2012-11-01T06:37:32.040 回答
0
$url = '/article/math/unit2/chapter3/para4';
$url=str_replace('/article/','','/article/math/unit2/chapter3/para4');
print_r(explode('/','/article/math/unit2/chapter3/para4'));
于 2012-11-01T06:38:06.280 回答
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
)
于 2012-11-01T06:41:30.247 回答