regex phone number validation with PHP

前端 未结 5 1296
孤独总比滥情好
孤独总比滥情好 2021-01-17 01:33

This is another question about a previous question I had asked yesterday. I want user to be allowed to type US phone numbers in the following formats.

(800)-555-121

5条回答
  •  青春惊慌失措
    2021-01-17 01:54

    This function validate a phone number, return true if it validate and false if invalid. This function very simple i was wrote to.

        /**
         * @param $number
         *
         * @return bool
         */
        function validatePhoneNumber($number) {
            $formats = [
                '###-###-####', '####-###-###',
                '(###) ###-###', '####-####-####',
                '##-###-####-####', '####-####', '###-###-###',
                '#####-###-###', '##########', '#########',
                '# ### #####', '#-### #####'
            ];
    
            return in_array(
                trim(preg_replace('/[0-9]/', '#', $number)),
                $formats
            );
        }
    

提交回复
热议问题