2012-11-01 155 views
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:$模式是动态模式。可以改变为“/条/ foo”的,“/条/富/栏”等

+0

对不起,$ pattern是动态的。不是$ url。 –

回答

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 
) 
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); 
+0

你能给我这个代码吗? –

+0

确定它在编辑中 – Zlug

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); 
2

使用explode()

$url = '/article/math/unit2/chapter3/para4'; 
$arrz = explode("/", $url); 
print_r($arrz); 
0
$url = '/article/math/unit2/chapter3/para4'; 
$url=str_replace('/article/','','/article/math/unit2/chapter3/para4'); 
print_r(explode('/','/article/math/unit2/chapter3/para4')); 
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 
)