I just want to know the method to check a PHP variable for any non-numbers and if it also detects spaces between characters? Need to make sure nothing weird gets put into my form fields. Thanks in advance.
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- how to split a list into a given number of sub-lis
- Can php detect if javascript is on or not?
PHP has the function is_numeric() which may be what you are looking for.
Assuming you want only (and only) valid integers and you dont want users to mess up with your data and database with
hexadecimal
orbinary
or any other form of numbers then you can always use this method:The trick is simple. It casts the variable of type string to integer type and then casts it back to string. Super fast, Super simple.
For the sake of testing I've prepared a test:
The only place that this method falls short is on negative numbers, so you need to check that beside this (use
((string) (int) $stringVariable) === $stringVariable && $stringVariable[0] !== "-"
).Now I thought that the
preg_match
method is the best. but in any project that deals with users, speed is an important factor. so I prepared a benchmarking test doing that above test for 500,000 times and the results were amazing:My own invented method took only:
6.4700090885162
seconds to complete as compared to
preg_match
which took:77.020107984543
seconds to complete this test!If you mean that you only want a value to contain digits then you can use
ctype_digit()
.