Php if string is only numbers

Php check if string contains numbers only php

Other Options There are other methods that have been suggested here and in other questions that will not achieve the stated goals , but I think it is important to mention them and explain why they won’t work as it might help someone else. allows exponential parts, floats, and hex values checks data type rather than value which is not useful for validation if is to be considered valid. If the goal is to fail fast , one would want to check for invalid values and then fail rather than checking for valid values and having to wrap all code in an block.

Checking that a value contains only digits, regex or no?

The Goal

The original question is about validating a value of unknown data type and discarding all values except those that contain nothing but digits . There seems to be only two ways to achieve this desired result.

If the goal is to fail fast , one would want to check for invalid values and then fail rather than checking for valid values and having to wrap all code in an if block.

Option 1 from Question

if (preg_match('/\D/', $company_id)) exit('Invalid parameter'); 

Using regex to fail if match non-digits. Con: regex engine has overhead

Option 2 from Question

if (!ctype_digit((string) $company_id)) exit('Invalid parameter'); 

Using ctype_digit to fail if FALSE. Con: value must be cast to string which is a (small) extra step

You must cast value to a string because ctype_digit expects a string and PHP will not cast the parameter to a string for you. If you pass an integer to ctype_digit , you will get unexpected results.

This is documented behaviour. For example:

ctype_digit('42'); // true ctype_digit(42); // false (ASCII 42 is the * character) 

Difference Between Option 1 and 2

Due to the overhead of the regex engine, option two is probably the best option. However, worrying about the difference between these two options may fall into the premature optimization category.

Note: There is also a functional difference between the two options above. The first option considers NULL and empty strings as valid values, the second option does not (as of PHP 5.1.0). That may make one method more desirable than the other. To make the regex option function the same as the ctype_digit version, use this instead.

if (!preg_match('/^\d+$/', $company_id)) exit('Invalid parameter'); 

Note: The ‘start of string’ ^ and ‘end of string’ $ anchors in the above regex are very important. Otherwise, abc123def would be considered valid.

Читайте также:  Специальные символы html пробел

Other Options

There are other methods that have been suggested here and in other questions that will not achieve the stated goals , but I think it is important to mention them and explain why they won’t work as it might help someone else.

  • is_numeric allows exponential parts, floats, and hex values
  • is_int checks data type rather than value which is not useful for validation if ‘1’ is to be considered valid. And form input is always a string. If you aren’t sure where the value is coming from, you can’t be sure of the data type.
  • filter_var with FILTER_VALIDATE_INT allows negative integers and values such as 1.0 . This seems like the best function to actually validate an integer regardless of data type. But doesn’t work if you want only digits. Note: It’s important to check FALSE identity rather than just truthy/falsey if 0 is to be considered a valid value.

What about filter_var + FILTER_VALIDATE_INT ?

if (FALSE === ($id = filter_var($_GET['id'], FILTER_VALIDATE_INT))) < // $_GET['id'] does not look like a valid int >else < // $id is a int because $_GET['id'] looks like a valid int >

Besides, it has min_range/max_range options.

The base idea of this function is more or less equivalent to :

function validate_int($string) < if (!ctype_digit($string)) < return FALSE; >else < return intval($string); >> 

Also, if you expect an integer, you could use is_int . Unfortunately, type hinting is limited to objets and array.

Both methods will cast the variable into a string. preg_match does not accept a subject of type integer so it will be cast to a string once passed to the function. ctype_digit is definitely the best solution in this case.

If string has only numbers php Code Example, check if string is number or not php ; 1. $var_num = «1»; ; 2. $var_str = «Hello World»; ; 3. ​ ; 4. var_dump( is_numeric($var_num), is_numeric($var_str) ); ; 5. ​.

PHP check if string has numbers together

Assuming phone number to be of 7 continuous digits at least, you can use negative lookbehind like

$re = "/^(. *\\d).*/m"; $str = "1234567\n123456\n12345673536"; preg_match_all($re, $str, $matches); print_r($matches); 

Ideone Demo

PHP: Check if my string only contains numbers and «X» character, Don’t use regular expression in such a trivial case. For example you can write your own domain parse function.

PHP: Check if my string only contains numbers and «X» character

Don’t use regular expression in such a trivial case. For example you can write your own domain parse function.

/** * Parse dimension * * @return array [dimX, dimY] or empty array when invalid input */ function parse(string $meta): array < $parseTree = explode('x', strtolower($meta)); if (2 != \count($parseTree) || !ctype_digit($parseTree[0]) || !ctype_digit($parseTree[1])) < return []; >return $parseTree; > /** * Test * @throws \LogicException When test failed */ function testParse() < $dataProvider = [ ['20x50', [20, 50]], ['20X50', [20, 50]], ['20z50', []], ['a20x50', []], ['20xa50', []], ]; foreach($dataProvider as $serie) < if (parse($serie[0]) != $serie[1]) < throw new \LogicException('Test failed'); >> > testParse(); 

Check if String has only Integers separated by comma in PHP

$re = '/^\d+(. \d+)*$/'; $str = '2323,321,329,34938,23123,54545,123123,312312'; if ( preg_match($re, $str) ) echo "correct format"; else echo "incorrect format"; 

Just for fun with no regex:

var_dump( !array_diff($a = explode(',', $str), array_map('intval', $a)) ); 

If you do not care about the format then you can just check for the characters:

$regex = '/^[0-9,]+$/'; if (preg_match($regex, $str) === 1)

You can also do it without using regular expressions:

$str = str_replace(',', '', $str); if (ctype_digit($str))

If you care about the format then something like this would work:

$regex = '/^4+(. 9+)*$/'; if (preg_match($regex, $str) === 1)

Detect if a string contains any numbers, It splits the string character by character and checks if the character is a number or not. Problem: Its output is always «This variable

Читайте также:  Где применяется язык программирования java

Источник

is_numeric

Determines if the given variable is a number or a numeric string.

Parameters

The variable being evaluated.

Return Values

Returns true if value is a number or a numeric string, false otherwise.

Changelog

Version Description
8.0.0 Numeric strings ending with whitespace ( «42 » ) will now return true . Previously, false was returned instead.

Examples

Example #1 is_numeric() examples

$tests = array(
«42» ,
1337 ,
0x539 ,
02471 ,
0b10100111001 ,
1337e0 ,
«0x539» ,
«02471» ,
«0b10100111001» ,
«1337e0» ,
«not numeric» ,
array(),
9.1 ,
null ,
» ,
);

foreach ( $tests as $element ) if ( is_numeric ( $element )) echo var_export ( $element , true ) . » is numeric» , PHP_EOL ;
> else echo var_export ( $element , true ) . » is NOT numeric» , PHP_EOL ;
>
>
?>

The above example will output:

'42' is numeric 1337 is numeric 1337 is numeric 1337 is numeric 1337 is numeric 1337.0 is numeric '0x539' is NOT numeric '02471' is numeric '0b10100111001' is NOT numeric '1337e0' is numeric 'not numeric' is NOT numeric array ( ) is NOT numeric 9.1 is numeric NULL is NOT numeric '' is NOT numeric

Example #2 is_numeric() with whitespace

$tests = [
» 42″ ,
«42 » ,
«\u9001» , // non-breaking space
«9001\u» , // non-breaking space
];

foreach ( $tests as $element ) if ( is_numeric ( $element )) echo var_export ( $element , true ) . » is numeric» , PHP_EOL ;
> else echo var_export ( $element , true ) . » is NOT numeric» , PHP_EOL ;
>
>
?>

Output of the above example in PHP 8:

' 42' is numeric '42 ' is numeric ' 9001' is NOT numeric '9001 ' is NOT numeric

Output of the above example in PHP 7:

' 42' is numeric '42 ' is NOT numeric ' 9001' is NOT numeric '9001 ' is NOT numeric

See Also

  • Numeric strings
  • ctype_digit() — Check for numeric character(s)
  • is_bool() — Finds out whether a variable is a boolean
  • is_null() — Finds whether a variable is null
  • is_float() — Finds whether the type of a variable is float
  • is_int() — Find whether the type of a variable is integer
  • is_string() — Find whether the type of a variable is string
  • is_object() — Finds whether a variable is an object
  • is_array() — Finds whether a variable is an array
  • filter_var() — Filters a variable with a specified filter
Читайте также:  Перестановка элементов массива python 9 класс

User Contributed Notes 8 notes

Note that the function accepts extremely big numbers and correctly evaluates them.

$v = is_numeric ( ‘58635272821786587286382824657568871098287278276543219876543’ ) ? true : false ;

var_dump ( $v );
?>

The above script will output:

So this function is not intimidated by super-big numbers. I hope this helps someone.

PS: Also note that if you write is_numeric (45thg), this will generate a parse error (since the parameter is not enclosed between apostrophes or double quotes). Keep this in mind when you use this function.

for strings, it return true only if float number has a dot

is_numeric( ‘42.1’ )//true
is_numeric( ‘42,1’ )//false

Apparently NAN (Not A Number) is a number for the sake of is_numeric().

echo «is » ;
if (! is_numeric ( NAN ))
echo «not » ;
echo «a number» ;
?>

Outputs «is a number». So something that is NOT a number (by defintion) is a number.

is_numeric fails on the hex values greater than LONG_MAX, so having a large hex value parsed through is_numeric would result in FALSE being returned even though the value is a valid hex number

is incorrect for PHP8, it’s numeric.

Note that this function is not appropriate to check if «is_numeric» for very long strings. In fact, everything passed to this function is converted to long and then to a double. Anything greater than approximately 1.8e308 is too large for a double, so it becomes infinity, i.e. FALSE. What that means is that, for each string with more than 308 characters, is_numeric() will return FALSE, even if all chars are digits.

However, this behaviour is platform-specific.

In such a case, it is suitable to use regular expressions:

function is_numeric_big($s=0) return preg_match(‘/^-?\d+$/’, $s);
>

Note that is_numeric() will evaluate to false for number strings using decimal commas.

regarding the global vs. american numeral notations, it should be noted that at least in japanese, numbers aren’t grouped with an extra symbol every three digits, but rather every four digits (for example 1,0000 instead of 10.000). also nadim’s regexen are slightly suboptimal at one point having an unescaped ‘.’ operator, and the whole thing could easily be combined into a single regex (speed and all).

$eng_or_world = preg_match
( ‘/^[+-]?’ . // start marker and sign prefix
‘((((9+)|(3(,7)+)))?(\\.4)?(7*)|’ . // american
‘(((4+)|(9(\\.7)+)))?(,4)?(9*))’ . // world
‘(e2+)?’ . // exponent
‘$/’ , // end marker
$str ) == 1 ;
?>

i’m sure this still isn’t optimal, but it should also cover japanese-style numerals and it fixed a couple of other issues with the other regexen. it also allows for an exponent suffix, the pre-decimal digits are optional and it enforces using either grouped or ungrouped integer parts. should be easier to trim to your liking too.

Источник

Оцените статью