Skip to content

Instantly share code, notes, and snippets.

@dave1010
Created September 13, 2011 15:46
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save dave1010/1214164 to your computer and use it in GitHub Desktop.
Save dave1010/1214164 to your computer and use it in GitHub Desktop.
php-regex-router.php
<?php
// dangerously simple PHP regular expression URL router
// requires a mod_rewrite like "RewriteRule . /index.php [L]"
function get($url, $callback) {
$matches = array();
if (preg_match('~' . $url . '~', $_SERVER['REQUEST_URI'], $matches)) {
echo call_user_func_array($callback, $matches);
die();
}
}
get('foo', function($url) {
return 'you got foo';
});
get('bar([\d])', function($url, $digit) {
return 'bar number ' . $digit;
});
get('.*', function() {
return 'catch all. try /foo or /bar[0-9]';
});
@abdulsalamIshaq
Copy link

to get rid of the first argument $url in the callback function, remove the first element in the array $matches using array_shift() function

function get($url, $callback) {
	$matches = array();
	if (preg_match('~' . $url . '~', $_SERVER['REQUEST_URI'], $matches)) {
                array_shift($url);
		return call_user_func_array($callback, $matches);
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment