Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
simple RoR style uri mapping snippet
<?php
$str = "/parent/:dbname/:collname/:id";
function uri2regex ($str, &$params_keys) {
$word = "([0-9a-zA-Z_-]+)";
$flag = preg_match_all("/:\w+/",$str, $matches);
$params = $matches[0];
array_walk($params, 'uriNormalize');
$ret = preg_replace("/:\w+/", $word, $str);
$ret = str_replace("/", "\/", $ret);
$params_keys = $params;
return "/^" . $ret . "/";
}
function uriNormalize (&$item) {
$item = str_replace(":", "", $item);
}
$pkeys = array();
$regex = uri2regex($str, $pkeys);
var_dump($regex);
$uri = "/parent/foo_db/bar_coll/200";
$flag = preg_match_all($regex, $uri, $matches);
$route = array();
array_shift($matches);
foreach ($pkeys as $key) {
$match = array_shift($matches);
$route[$key] = array_shift($match);
}
var_dump($route);
/*
output:
string(65) "/^\/parent\/([0-9a-zA-Z_-]+)\/([0-9a-zA-Z_-]+)\/([0-9a-zA-Z_-]+)/"
array(3) {
["dbname"]=>
string(6) "foo_db"
["collname"]=>
string(8) "bar_coll"
["id"]=>
string(3) "200"
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.