Detecting whether number string or operator/letter string in PHP? - php

In PHP, how do I distinguish between a number as a string [0-9] versus an operator (+-*/) or letter [A-Za-z]?
I tried this, but intval also converts the type of nonnumbers to ints as well:
is_int(intval($somestr));
Is regex the way to do it?

Use the ctype functions. E.g.:
$isNumeric = ctype_digit('123123');

Try is_numeric().
is_numeric gives true by f. ex. 1e3 or 0xf5 too. So it's not the same as ctype_digit, which just gives true when only values from 0 to 9 are entered.

Related

RegEx not fully correct [duplicate]

I want user only input 0-9 and only once "."
patt = /[^0-9(.{1})]/
1.2222 -> true
1.2.2 -> false (only once '.')
help me , thank !
/^-?(?:\d+|\d*\.\d+)$/
This matches normal floats e.g. 3.14, shorthands for decimal part only e.g. .5 and integers e.g. 9 as well as negative numbers.
this is what you're looking for
$re = "~ #delimiter
^ # start of input
-? # minus, optional
[0-9]+ # at least one digit
( # begin group
\. # a dot
[0-9]+ # at least one digit
) # end of group
? # group is optional
$ # end of input
~xD";
this only accepts "123" or "123.456", not ".123" or "14e+15". If you need these forms as well, try is_numeric
Regular Expressions are for matching string patterns. If you are not explicitly after validating the input string's format (but the actual value), you can also use
filter_var("1.33", FILTER_VALIDATE_FLOAT);
to make sure the input can be used as a float value. This will return FALSE if it is not a float and the float or integer value otherwise. Any type juggling rules apply.
This regex:
\d*(?:\.\d+)?
will give results:
123 -> true
123.345 -> true
123. -> true
.345 -> true
0.3345 -> true
However, you must check emptiness of the input before using it because the regex also permit zero-length input.
You can use is_numeric() with the caveat that it accepts a bit more than one usually wants (e.g. 1e4).
I wrote the following regex that seems to work best for my test inputs so far,
/^-?(\d|[1-9]+\d*|\.\d+|0\.\d+|[1-9]+\d*\.\d+)$/
It matches integer using the first two alternatives
\d|[1-9]+\d*
Then it look for numbers like .5, .55, .05 etc., that is beginning with a .
\.\d+
Then it looks for the same as previous but a 0 before the .
0\.\d+
Then finally it looks for patterns integer and decimal parts, such as 5.5, 5.05 etc.
[1-9]+\d*\.\d+
You can test the regex in this link
Validate float - regex101
Why not use http://php.net/manual/en/function.is-float.php ? But anyhow, the RegEx would be ^[\d]+(|\.[\d]+)$ have fun!
Why not just use is_numeric if you're not experienced with regular expressions.
As to your regex: . matches all characters, \. matches a dot. {1} is not necessary. And I have no clue what you're trying to do with [^ ... ]. Read the regular expressions tutorial if you really want to use regular expressions somewhere in your code.

How to check if variable is Alphabetic or Numeric in PHP?

How to check if variable is Alphabetic or Numeric in PHP?
Depending on how you define numeric, you'll use one of the following functions :
is_numeric
ctype_digit
With the first one, numeric is defined as (quoting) :
Numeric strings consist of optional
sign, any number of digits, optional
decimal part and optional exponential
part.
While, with the second one, you will (quoting) :
Checks if all of the characters in the
provided string, text, are numerical
And, for alphabetic, you'll be interested by :
ctype_alpha
Quoting :
Checks if all of the characters in the
provided string, text, are alphabetic.
In the standard C locale letters are
just [A-Za-z]
And, as pointed out by #Long Ears in his comment, if you want to check both in a single shot, you'll find the ctype_alnum() function (quoting) :
Checks if all of the characters in the
provided string, text, are
alphanumeric.
In any case, you might want to take a look at the full list of Ctype functions.
Use the is_numeric function:
is_numeric("42"); // true
is_numeric(1337); // true
is_numeric("1e4"); // true
is_numeric("not numeric"); // false
is_numeric(Array()); // false
is_numeric(9.1); // true
You can use is_numeric() or ctype_alpha() functions
you quick test the input val by if numeric or alpha`enter code here`
using this php function
if(ctype_alnum($eafrik)){
echo "is alphatnumeric";
}else{
echo "is not alphanumeric"
}

What is wrong with this simple line of PHP?

is_int($_GET['pid']) ? define(PRODUCT, $_GET['pid']) : die('Invalid Product Id');
even if the value of pid is an integer I still get the Invalid product id message. Why?
Like the manual says: To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric().
Edit: Though it's implied by my answer here, I'll be more specific: $_GET's contents is strings, so an is_int call will always return false. If what you really want to verify here is that the contents of a particular string represents a integer number, you can use a call to is_numeric.
values in the $_GET array are usually type string, but sometimes type array as well.
use ctype_digit() to check if a string is entirely digit characters. optionally, trim() the string first. only use is_numeric() if you want to accept strings in a wide range of formats that are sometimes interpreted numerically, such as decimals, scientific notation, hex strings etc...
$_GET[] always returns strings, so is_int() always evaluates to false. Try is_numeric() instead.
Anything in $_GET is string, and is_int("2") returns false.

PHP comparison '==' problem

Why is the output 'in'?
<?php
if (1=='1, 3')
{
echo "in";
}
?>
The == operator does type conversion on the two values to try to get them to be the same type. In your example it will convert the second value from a string into an integer, which will be equal to 1. This is then obviously equal to the value you're matching.
If your first value had been a string - ie '1' in quotes, rather than an integer, then the match would have failed because both sides are strings, so it would have done a string comparison, and they're different strings.
If you need an exact match operator that doesn't do type conversion, PHP also offers a tripple-equal operator, ===, which may be what you're looking for instead.
Hope that helps.
Because PHP is doing type conversion, it's turning a string into an integer, and it's methods of doing so work such that it counts all numbers up until a non-numeric value. In your case that's the substring ('1') (because , is the first non-numeric character). If you string started with anything but a number, you'd get 0.
You are comparing a string and an integer. The string must be converted to an integer first, and PHP converts numeric strings to integers. Since the start of that string is '1', it compares the number one, with the number one, these are equal.
What functionality did you intend?
If you're trying to check if 1 is equal to 1 or 3, then I would definitely do it this way:
if (1 == 1 || 1 == 3)
Please refer to the PHP documentation:
http://php.net/manual/en/language.operators.comparison.php
The output should be:
in
From PHP's documentation:
When converting from a string to an
integer, PHP analyzes the string one
character at a time until it finds a
non-digit character. (The number may,
optionally, start with a + or - sign.)
The resulting number is parsed as a
decimal number (base-10). A failure to
parse a valid decimal number returns
the value 0.
I'm guessing you want to know whether a variable is in a range of values.
You can use in_array:
if (in_array(1, array(1, 3, 5, 6)))
echo "in";
if(in_array(1, array(1,3)) {
echo "in";
}

is_numeric or a numeric preg_match?

I read on a forum that you can't completely trust is_numeric(). It lets through "0xFF" for example which is an allowed hexadecimal...
So my question is can you trick is_numeric? Will I need to use a regex to do it correctly?
Here is what is_numeric() considers to be a numeric string:
Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus +0123.45e6 is a valid numeric value. Hexadecimal notation (0xFF) is allowed too but only without sign, decimal and exponential part.
If you only want to check if a string consists of decimal digits 0-9, you could use ctype_digit().
One can also check using ctype_digit() to check if its a true number.
Regex would obviously be your better option, however it does come with an overhead. So it really depends on your situation and what you want to do.
Is it for validating user input? Then the overhead of using a regexp or asserting it doesn't contain an "x" and is_numeric() wouldn't be too much overhead.
If you just want to check that something is an integer, try this:
function isInteger($value){
return (is_numeric($value) ? intval($value) == $value : false);
}
If you want to check for floats too then this won't work obviously :)

Categories