Skip to content

Instantly share code, notes, and snippets.

@sp3c73r2038
Created January 11, 2012 04:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sp3c73r2038/1592977 to your computer and use it in GitHub Desktop.
Save sp3c73r2038/1592977 to your computer and use it in GitHub Desktop.
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