Here is the match_url function I am using at the moment
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;
}
}
}
Here are some example $urls
$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()
);
the following url articles/2010 would return an array like:
Array
(
[controller] => articles
[action] => show
[name] => article_view
[args] => Array
(
[year] => 2010
)
)
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:
$name = "article_view";
$args = array("year"=>2010);
echo url_for($name,$args);
//should output articles/2010
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.