2013-07-31 147 views
1

我有一個網址,我想匹配特定的模式正則表達式匹配一切後,

/事件/顯示/ ID /特色

  • 比賽後一切地方/ events/
  • 顯示器與鍵匹配
  • id和featured有1個或多個相映成關鍵

因此我最終

Array (
[method] => display 
[param] => Array ([0]=>id,[1]=>featured,[2]=>true /* if there was another path */) 
) 

到目前爲止,我已經

(?:/events/)/(?P<method>.*?)/(?P<parameter>.*?)([^/].*?) 

但它不工作了預期。

語法有什麼問題?

P.S.不,我不想用parse_url()或者PHP定義的函數我需要一個正則表達式

+2

你有一個額外/事件之後:它尋找/事件//方法 – JDiPierro

回答

2

您可以使用此模式:

<pre><?php 
$subject = '/events/display/id1/param1/id2/param2/id3/param3'; 

$pattern = '~/events/(?<method>[^/]++)|\G/(?<id>[^/]++)/(?<param>[^/]++)~'; 

preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER); 

foreach($matches as $match) { 
    if (empty($match['method'])) { 
     $keyval[] = array('id'=>$match['id'], 'param'=>$match['param']); 
    } else { 
     $result['method'] = $match['method']; 
    } 
} 
if (isset($keyval)) $result['param'] = $keyval; 
print_r($result); 

花樣細節:

~ 
/events/(?<method>[^/]++) # "events" followed by the method name 
|       # OR 
\G       # a contiguous match from the precedent 
/(?<id>[^/]++)    # id 
/(?<param>[^/]++)   # param 
~ 
+0

新的通信規則上那麼告訴我不應該這樣做,但卻,我會:+1好的解決方案! :) – hek2mgl

+0

@ hek2mgl:謝謝!我不會對任何人說。 –

2

爲什麼不使用的preg_match()explode()混合:

$str = '/events/display/id/featured'; 
$pattern = '~/events/(?P<method>.*?)/(?P<parameter>.*)~'; 
preg_match($pattern, $str, $matches); 

// explode the params by '/' 
$matches['parameter'] = explode('/', $matches['parameter']); 
var_dump($matches); 

輸出:

array(5) { 
    [0] => 
    string(27) "/events/display/id/featured" 
    'method' => 
    string(7) "display" 
    [1] => 
    string(7) "display" 
    'parameter' => 
    array(2) { 
    [0] => 
    string(2) "id" 
    [1] => 
    string(8) "featured" 
    } 
    [2] => 
    string(11) "id/featured" 
} 
0

這裏我基本上使用preg_match_all()重現類似explode()功能。然後我將結果重新映射到一個新數組。不幸的是,單靠Regex無法做到這一點。

<?php 

$url = '/events/display/id/featured/something-else'; 
if(preg_match('!^/events!',$url)){ 
    $pattern = '!(?<=/)[^/]+!'; 
    $m = preg_match_all($pattern,$url,$matches); 

    $results = array(); 

    foreach($matches[0] as $key=>$value){ 
     if($key==1){ 
      $results['method']=$value; 
     } elseif(!empty($key)) { 
      $results['param'][]=$value; 
     } 
    } 
} 

print_r($results); 

?> 

輸出

Array 
(
    [method] => display 
    [param] => Array 
     (
      [0] => id 
      [1] => featured 
      [2] => something-else 
     ) 

)