Reputation: 2869
I'm using this to determine if a string looks like the right url, and then extract a value
if (preg_match('#^(https?:\/\/)?(www.)?site.com\/cat\/(aaa\d{5,30})\/#', $url, $urlid)) {
echo $urlid[3];
}
It works ok, but I think it could be more lean/improved (or just more good-practice). Should I add some "negative look-ahead", "non-capturing" or other?
This for example (https?:\/\/)?(www.)?
was just a quick thought. It works, but... Should it really be in parentheses or is there a better way?
Upvotes: 1
Views: 48
Reputation: 89547
You can write it like this:
if (preg_match('~^(?:https?://)?(?:www\.)?site\.com/cat/(aaa\d{5,30})/~', $url, $urlid))
echo $urlid[1];
Improvements:
(?:...)
/
when it is not used as delimiter.
otherwise it is not seen as a literal characterBenefits:
\.
matches a dot and not an other characterUpvotes: 1