Re: Only numbers

From: Date: Thu, 15 May 2003 18:36:22 +0000
Subject: Re: Only numbers
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-147765@lists.php.net to get a copy of this message
> Is there any way to make sure that only numbers are entered into the > database from a form? > > Eg: > I have a form that has $phone_number, i dont want "89888-23323" or > "asdfasdf" there....only numbers... > what to do? I was going to suggest is_numeric(), but you could have a value such as -123.45E8 that would pass. So, use something like this: if(preg_match('/[^0-9]/',$data)) { echo "failed!"; } else { echo "passed!"; } Here's a suggestion, though. I always like to allow my users to enter the data in as many formats as they want, then just have PHP format it for me. So, what you may want to do is just take the data they give you and replace anything that's not numeric with an empty string: $new_data = preg_replace('/[^0-9]/','',$data); So (123) 456-9876 will be turned into 1234569876 and you can save it. Or you could just match the characters (, ), -, and a space and replace those. If any other characters are present, throw an error because it's probably an invalid number. Hope that helps. ---John Holmes...

« previous php.general (#147765) next »