preg_match function for phone numbers

折月煮酒 提交于 2019-12-06 12:43:12

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!