preg function

Discussion in 'PHP' started by bumbar, Mar 2, 2014.

  1. #1
    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.
     
    bumbar, Mar 2, 2014 IP
  2. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #2
    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.
     
    deathshadow, Mar 2, 2014 IP
  3. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #3
    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".)
     
    nico_swd, Mar 2, 2014 IP
  4. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #4
    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 :D

    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):
     
    deathshadow, Mar 2, 2014 IP
  5. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #5
    Haha, that would have been kinda awesome!
     
    nico_swd, Mar 2, 2014 IP