问题
I have some troubles matching a phone number with this function
return (bool)preg_match( '/^[\-+]?[0-9]+$/', $num);
The above function always returns false after stripping brackets ( )
and dash -
am left with +1234567890
what am i missing
回答1:
Test Here: https://eval.in/84659
$p = '/[\-+]?[0-9]+$/';
$num ='+1234567890';
echo preg_match( $p, $num)." ";
$num1 ='+1234567890d';
echo preg_match( $p, $num1)." ";
$num1 ='-1234567890';
echo preg_match( $p, $num1)." ";
OUTPUT:
1 0 1
回答2:
You probably have some whitespace in the string. Try using trim
return (bool)preg_match( '/^[\-+]?[0-9]+$/', trim($num));
回答3:
For North American phone numbers only, you could use this
^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$
来源:https://stackoverflow.com/questions/20871160/preg-match-function-for-phone-numbers