tags:

views:

37

answers:

1

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.

+1  A: 

Here is the solution I came up with:

function url_for($urls,$name,$args) {
    $url = "";
    foreach($urls as $k=>$v) {
        if(!empty($v['name']) && $v['name'] == $name) {
            $url = $k;
            foreach($args as $key=>$value) {
                $url = preg_replace("/\(\?P\<$key\>(.*)\)/",$value,$url);
            }
        }
    }
    return $url;
}

Which now works as I expected

tomfmason