Created
January 11, 2012 04:16
-
-
Save sp3c73r2038/1592977 to your computer and use it in GitHub Desktop.
simple RoR style uri mapping snippet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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