Need help with regular expression for URLs
Was just parsing urls of the type http://sitename.com/catid/300/, http://sitename.com/catid/341/ etc etc
开发者_JS百科wherein the parameter after the catid (300,341) are only integers. When I use the following condition in .htaccess, it works fine
RewriteRule ^(abc|def|hij|klm)/([0-9]+)/$ /index3.php?catid=$1&postid=$2 [L]
but when a php regex match function,like preg_match, it returns 1 for alphanumeric numbers too
eg: echo preg_match('([0-9]+)','a123'); or echo preg_match('([0-9]+)',a123);
They both return 1 ()true. I dont know why it matches alphanumerics. I want it to match only numbers.
What am I doing wrong?
Without anchors, it will match the numbers regardless of what comes before or after them. Try it with anchors:
/^([0-9]+)$/
If you don't need to capture, try this:
/^[0-9]+$/
Results:
php > echo preg_match('([0-9]+)','a123');
1
php > echo preg_match('/^[0-9]+$/','a123');
0
php > echo preg_match('/^[0-9]+$/',0.65);
0
php > echo preg_match('/^[0-9]+$/',666);
1
Regular expressions are not always the answer. If you are just checking for a number, try is_numeric. If you just want an integer, try is_int.
Try preg_match('/^[0-9]+$/','a123');
精彩评论