我有一个我想要匹配特定模式的网址
/活动/显示/ ID /功能
其中
因此我最终得到了
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定义的函数,我需要一个正则表达式
答案 0 :(得分: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"
}
答案 1 :(得分: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
~
答案 2 :(得分: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
)
)