Hello, I have this function to validate phone numbers. Only digits... function validatePhoneNumber($number){ $formats = array( '##########', '#########', '#####', '######', ); $format = trim(preg_replace("/[0-9]/", '#', $number)); return (in_array($format, $formats)) ? true : false; } Code (markup): The problem is /[0-9]/ . If I put 0 in argument, the function in not work. I test with /[^0-9]/ but no result.... How to validate number if the phone starts with zero or contains zero? Thanks.
I wouldn't use a regex for that. function validatePhoneNumber($number){ $number = trim($number); $length = count($number); return is_numeric($number) && ( ($length == 5) || ($length == 6) || ($length == 9) || ($length == 10) ); } Code (markup): Since that's all your testing for -- is it a number and is it a valid length.
is_numeric() is a little funny, though. var_dump(is_numeric('0xfffffffff')); // bool(true) PHP: I would probably use ctype_digit() instead. (And I'm pretty sure you meant "strlen" instead of "count".)
Right on both counts -- I'm switching languages WAY too much lately. I almost posted the answer in Z80 assembly given where my head's at right now So that should have been: function validatePhoneNumber($number){ $number = trim($number); $length = strlen($number); return ctype_digit($number) && ( ($length == 5) || ($length == 6) || ($length == 9) || ($length == 10) ); } Code (markup):