0

Was just parsing urls of the type http://sitename.com/catid/300/, http://sitename.com/catid/341/ etc etc

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?

1
  • 1
    Your preg_match basically boils down to "match if there's one or more digits ANYWHERE in the string" Commented Jul 22, 2011 at 16:32

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

using echo preg_match('^[0-9]+$','a123'); gives this error 'No ending delimiter '^' found'
thanks bu the following case... preg_match('/^[0-9]+$/',0.65); also returns true (0). :(
It worked for me. I updated the results in my answer to show this.
1

Try preg_match('/^[0-9]+$/','a123');

1 Comment

thanks mate but preg_match('/^[0-9]+$/',0.65); also returns true (0).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.