Number of php regular expressions and + sign

I need a php function to check a string, so it can only contain a number and a plus (+) sign in front.

Example:

+632444747 will return true 632444747 will return true
632444747 + will return false
and 632444747 will return false

How to do it with regular expression?

Thanks.

+7
source share
2 answers

Something like that

preg_match('/^\+?\d+$/', $str); 

Testing

 $strs = array('+632444747', '632444747', '632444747+', '&632444747'); foreach ($strs as $str) { if (preg_match('/^\+?\d+$/', $str)) { print "$str is a phone number\n"; } else { print "$str is not a phone number\n"; } } 

Exit

 +632444747 is a phone number 632444747 is a phone number 632444747+ is not a phone number &632444747 is not a phone number 
+20
source
 <?php var_dump(preg_match('/^\+?\d+$/', '+123')); var_dump(preg_match('/^\+?\d+$/', '123')); var_dump(preg_match('/^\+?\d+$/', '123+')); var_dump(preg_match('/^\+?\d+$/', '&123')); var_dump(preg_match('/^\+?\d+$/', ' 123')); var_dump(preg_match('/^\+?\d+$/', '+ 123')); ?> 

only the first 2 (1) will be true. others are all false (0).

+1
source

All Articles