反向preg_replace - 路由器

时间:2013-08-27 12:27:53

标签: php preg-replace router

我有路由的数组:

$route = array(
    '/home/news/([0-9])'=>'/home/news/id/$1'
    );    

我有检查请求的脚本&的Valide。所以我可以跑:

http://mysite.com/home/news/id/4 (run: controller: home, action: news, param id: 4 -> this is defaults)

AND

http://mysite.com/home/news/4 (run: controller: home, action: news, param id: 4 -> look route array [up])

脚本:

$request = '/home/news/id/10'; //example
foreach($route as $r => $key) {
            $r = str_replace('/', '\\/', $r);
            if(preg_match('/^'.$r.'$/',$request)) {
                $request = preg_replace('/^'.$r.'$/i',$key,$request);
                break;
            }

所以我现在想要反过来所有:

function createUrl($array) {
  //search in route value and if is ok return key array 
}

示例:

echo createUrl(array('controller'=>'home','action'=>'news','id'=>4)); //if not exists in route return: /home/news/id/4 but if exists reutnr /home/news/4

对不起我的英语:D

1 个答案:

答案 0 :(得分:0)

为什么不简单地创建:

function createUrl($route) {
   return $route['controller'].'/'.$route['action'].'/'.$route['id'] ;
}

然后,如果您显示信息:

createurl(array('controller'=>'home','action'=>'news','id'=>2));

您将获得预期的结果。 您还可以在函数内添加验证器以检查输入参数。

相关问题