I want to check if a variable has a number in it, I just want to see if there is one I don't care if it has any thing else in it like so:
"abc" - false
"!./#()" - false
"!./#()abc" - false
"123" - true
"abc123" - true
"!./#()123" - true
"abc !./#() 123" -true
There are easy ways of doing this if you want to know that is all numbers but not if it just has one. Thanks for your help.
To check if given string is a number or not, use PHP built-in function is_numeric(). is_numeric() takes string as an argument and returns true if the string is all numbers, else it returns false.
The key difference between these two functions is that is_int() checks the type of variable, while is_numeric() checks the value of the variable. $var = "123"; $var is a string of numbers, not an integer value.
The is_numeric() function is an inbuilt function in PHP which is used to check whether a variable passed in function as a parameter is a number or a numeric string or not. The function returns a boolean value.
PHP converts the string to an int, which is 0 (as it doesn't contain any number representation).
You can use the strcspn
function:
if (strcspn($_REQUEST['q'], '0123456789') != strlen($_REQUEST['q']))
echo "true";
else
echo "false";
strcspn
returns the length of the part that does not contain any integers. We compare that with the string length, and if they differ, then there must have been an integer.
There is no need to invoke the regular expression engine for this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With