I am trying to create a url router in PHP, that works like django’s.
The problems is, I don’t know php regular expressions very well.
I would like to be able to match urls like this:
/post/5/
/article/slug-goes-here/
I’ve got an array of regexes:
$urls = array(
"(^[/]$)" => "home.index",
"/post/(?P<post_id>\d+)/" => "home.post",
);
The first regex in the array works to match the home page at / but I can’t get the second one to work.
Here’s the code I am using to match them:
foreach($urls as $regex => $mapper) {
if (preg_match($regex, $uri, $matches)) {
...
}
}
I should also note that in the example above, I am trying to match the post_id in the url: /post/5/ so that I can pass the 5 along to my method.
You must delimit the regex. Delimiting allows you to provide ‘options’ (such as ‘i’ for case insensitive matching) as part of the pattern:
here, I have delimited the regex with commas.
As you have posted it, your regex was being delimited with /, which means it was treating everything after the second / as ‘options’, and only trying to match the “post” part.
The example you are trying to match against looks like it isn’t what you’re actually after based on your current regex.
If you are after a regex which will match something like;
Then, the following:
will result in:
Hopefully that clears it up for you 🙂
Edit
Based on the comment to your OP, you are only trying to match a number after the /post/ part of the URL, so this slightly simplified version:
will result in: