build url from regex string containing named subpattern

AmyS

New Member
Here is the match_url function I am using at the moment\[code\]function match_url($urls,$url) { foreach($urls as $regex=>$args) { $r = str_replace('/','\/',$regex); preg_match("/$r/i",$url,$matches); if(count($matches) > 0) { $dispatch = array(); $args['args'] = array(); if(empty($args) && !empty($matches['controller'])) { $dispatch['controller'] = $matches['controller']; $dispatch['action'] = $matches['action']; } else { foreach($matches as $k=>$v) { if(is_string($k)) { $args['args'][$k] = $v; } } $dispatch = $args; } return $dispatch; } }}\[/code\]Here are some example $urls\[code\]$urls = array( 'articles/(?P<year>\d{4})' => array('controller'=>'articles','action'=>'show','name'=>'article_view'), 'admin/(?P<controller>[-\w]+)/(?P<action>[-\w]+)' => array(), '(?P<controller>[-\w]+)/(?P<action>[-\w]+)' => array());\[/code\]the following url articles/2010 would return an array like:\[code\]Array([controller] => articles[action] => show[name] => article_view[args] => Array([year] => 2010))\[/code\]This works as expected but now I am wanting to create a function that will allow me to build a url from given url name and args. For example:\[code\]$name = "article_view";$args = array("year"=>2010);echo url_for($name,$args);//should output articles/2010\[/code\]The part that I am having trouble with is figuring out how I can replace the variables from the url regex with the passed args.Is there a simple method of doing this?Any suggestions or pointers in the right direction would be great.
 
Back
Top