I already wrote a PHP controller, but I'm rewriting my code, so I can have JSON routes with base routers that map URI patterns to combinations of PHP Class :: methods or directly to HTML documents that are then passed to the client, for example:
{ "/home" : "index.html", "/podcasts": "podcasts.html", "/podcasts/:param1/:param2": "SomeClass::someMethod" }
The array dynamically creates regular expressions to map routes to URLs. I took a look at the trunk code and I extracted the following code (slightly modified):
function _routeToRegExp (route) { var optionalParam = /\((.*?)\)/g; var namedParam = /(\(\?)?:\w+/g; var splatParam = /\*\w+/g; var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g; route = route.replace(escapeRegExp, '\\$&') .replace(optionalParam, '(?:$1)?') .replace(namedParam, function(match, optional){ return optional ? match : '([^\/]+)'; }) .replace(splatParam, '(.*?)'); return new RegExp('^' + route + '$'); }
When I pass the route, for example /podcasts/:param1/:param2 , to the code above, I get /^\/podcasts\/([^\/]+)\/([^\/]+)$/ . I tried to write a PHP function to get the exact same regular expression. I tried:
$route = '/podcasts/:param1/:param2'; $a = preg_replace('/[\-{}\[\]+?.,\\\^$|#\s]/', '\\$&', $route); // escapeRegExp $b = preg_replace('/\((.*?)\)/', '(?:$1)?', $a); // optionalParam $c = preg_replace('/(\(\?)?:\w+/', '([^\/]+)', $b); // namedParam $d = preg_replace('/\*\w+/', '(.*?)', $c); // splatParam $pattern = "/^{$d}$/"; echo "/^\/podcasts\/([^\/]+)\/([^\/]+)$/\n"; echo "{$pattern}\n"; $matches = array(); preg_match_all($pattern, '/podcasts/param1/param2', $matches); print_r($matches);
My conclusion:
/^\/podcasts\/([^\/]+)\/([^\/]+)$/ // The expected pattern /^/podcasts/([^\/]+)/([^\/]+)$/ // echo "{$pattern}\n"; Array // print_r($matches); ( )
Why is my regex output different? I can process the rest of the matching process and that’s it, but I didn’t understand how to get exactly the same regular expression in PHP as in Javascript. Any suggestions?