I have URLs like below that need to be recognized by the PHP code. Based on what the URL is, data needs to be shown:
www.example.com/music/username/popular
http://www.example.com/music/username/recent/
http://example.com/music/username/favorites/ignore_this /*Ignore everything after favorites*/
http://www.example.com/music/2011/05/02 /*Shows all music uploaded on this date*/
www.example.com/groups
http://www.example.com/groups/jazz
http://example.com/places/japan/?param=ignore_this /*Ignore everything after japan*/
www.example.com/search/rock/
The first URL should show a user’s popular music. www.example.com/groups should list all public groups. And so on..
http://is optional/at the end is optional- If anything (like
groups) is entered in UPPERCASE, it should be converted to lowercase
What is the best way to recognize these URLs, using regex and create a Switch case? Example snippet would be great.
Here is the system I use (it’s OOP, but you can change easily if you don’t like classes).
Note that
(?: )regexp is a non-matching subpattern, so it doesn’t affect anything.One example for your the case you provided:
?means the last/may not exist. Note that there is no$sign at the end, which means everything afterfavoriteswill be ignored. Theimodifier (after#) means the text case is not important.$this->requestis an instance ofclass Request, here it is: