Regular expression for patterns in CodeIgniter URIs
-
30-09-2019 - |
Question
I have another question asked her on Stack Overflow and was suggested to use regular expressions instead of PHP code. Unfortunately I don’t know regexp, and have tried many times in the past and now to understand it without success. So hopefully, if I ask nicely, someone here could help. I would be very grateful.
What I’m trying to achieve is so route different URI requests to different places, 4 to be specific. What would be a proper reg exp to match the following:
year
(example:2010
)year-month
(example:2010-nov
) (the month represented by 3 chars)year-month-day
(example:2010-nov-10
)year-month-day-string
(example:2010-nov-10-blog-post-title-here
)
I’m coding in PHP and using the CodeIgniter framework.
Regards, Jason
Solution
Since you are validating later. you can go really generic:
([0-9]{4})-([a-z]{3})-([0-9]{1,2})-([\w*](-?[\w*])*)
4 digits year, a hyphen, a 3 char lowercase word, a hyphen, two digits, at least one word, (optional hyphen and another word repeated as needed.)
OTHER TIPS
Year is
(19|20)\d\d
.Year-month is
(19|20)\d\d\-[a-z]{3}
Year-month-day is
(19|20)\d\d\-[a-z]{3}\-[1-3][0-9]
Year-month-day-string is
(19|20)\d\d\-[a-z]{3}\-[1-3][0-9]\-[a-z\-]*
Correct me if I'm wrong, please. Also note that there is no validation for month names or dates that don't really exist.