Jump to content

[SOLVED] Check if string contains anything other than numbers.


Warptweet

Recommended Posts

I have some forms on my site, and some of them require that you can only type in numbers, that means no decimals either. How can I check a string to see if it contains letters, decimals, or any of those complicated signs. AKA: Check if theres anything other than numbers 1-9

 

Thank you so much for any help!

Ahhh, mine was just a regular expression....

 

I didn't think to use teng's method....

 

Extending on teng's, you could also do:

 

$input = $_POST['input'];
$iinput = (int) $input;
if($input != $iinput) {
     //not numeric
}

 

That might cause PHP to throw a notice or warning though....  Not sure.

Ahhh, mine was just a regular expression....

 

I didn't think to use teng's method....

 

Extending on teng's, you could also do:

 

$input = $_POST['input'];
$iinput = (int) $input;
if($input != $iinput) {
     //not numeric
}

 

That might cause PHP to throw a notice or warning though....  Not sure.

 

wont work because int will remove ZERO in front of your string right?

eg.. this will give  (int)' 0005'  >>>5

 

 

It's also extremely fast....  It took half the time as converting the input to int and left trimming 0s on my comp.

 

It even beat:

$iput = (int) $input;

if($iput == 0 && $input != 0) {

}

 

By .09 seconds with 100,000 runs....

You could use is_numeric and strpos($input, '.').

 

Oddly enough, is_numeric combined with strpos is like .0001 seconds faster when the input isn't numeric, but when it is numeric, thus it has to continue to the strpos check, it's like 2.2 times slower lol....

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.