preg_match function for phone numbers

核能气质少年 提交于 2019-12-04 21:57:37

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   

You probably have some whitespace in the string. Try using trim

return (bool)preg_match( '/^[\-+]?[0-9]+$/', trim($num));

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