Php проверить содержит ли строка цифры

PHP is_numeric() Function

Check whether a variable is a number or a numeric string, or not:

$b = 0;
echo «b is » . is_numeric($b) . «
«;

$c = 32.5;
echo «c is » . is_numeric($c) . «
«;

$d = «32»;
echo «d is » . is_numeric($d) . «
«;

$e = true;
echo «e is » . is_numeric($e) . «
«;

$f = null;
echo «f is » . is_numeric($f) . «
«;
?>

Definition and Usage

The is_numeric() function checks whether a variable is a number or a numeric string.

This function returns true (1) if the variable is a number or a numeric string, otherwise it returns false/nothing.

Syntax

Parameter Values

Technical Details

Return Value: TRUE if variable is a number or a numeric string, FALSE otherwise
Return Type: Boolean
PHP Version: 4.0+

❮ PHP Variable Handling Reference

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

is_numeric

Определяет, является ли данная переменная числом или строкой, содержащей число.

Список параметров

Возвращаемые значения

Возвращает true , если value является числом или строкой, содержащей число или false в противном случае.

Список изменений

Версия Описание
8.0.0 Строки, состоящие из чисел, заканчивающиеся пробелом ( «42 » ), теперь будут возвращать true . Ранее вместо этого возвращалось false .

Примеры

Пример #1 Примеры использования is_numeric()

$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 ;
>
>
?>

Результат выполнения данного примера:

42 - число 1337 - число 1337 - число 1337 - число 1337 - число 1337.0 - число '0x539' - НЕ число '02471' - число '0b10100111001' - НЕ число '1337e0' - число 'not numeric' - НЕ число array ( ) - НЕ число 9.1 - число NULL - НЕ число '' - НЕ число

Пример #2 Пример использования is_numeric() с пробелом

$tests = [
» 42″ ,
«42 » ,
«\u9001» , // неразрывный пробел
«9001\u» , // неразрывный пробел
];
foreach ( $tests as $element ) if ( is_numeric ( $element )) echo var_export ( $element , true ) . » — число» , PHP_EOL ;
> else echo var_export ( $element , true ) . » — НЕ число» , PHP_EOL ;
>
>
?>

Результат выполнения данного примера в PHP 8:

' 42' - число '42 ' - число ' 9001' - НЕ число '9001 ' - НЕ число

Результат выполнения данного примера в PHP 7:

' 42' - число '42 ' - НЕ число ' 9001' - НЕ число '9001 ' - НЕ число

Смотрите также

  • Строки, содержащие числа
  • ctype_digit() — Проверяет наличие цифровых символов в строке
  • is_bool() — Проверяет, является ли переменная булевой
  • is_null() — Проверяет, является ли значение переменной равным null
  • is_float() — Проверяет, является ли переменная числом с плавающей точкой
  • is_int() — Проверяет, является ли переменная целым числом
  • is_string() — Проверяет, является ли переменная строкой
  • is_object() — Проверяет, является ли переменная объектом
  • is_array() — Определяет, является ли переменная массивом
  • filter_var() — Фильтрует переменную с помощью определённого фильтра
Читайте также:  Python whl what is it

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
‘((((2+)|(9(,8)+)))?(\\.3)?(1*)|’ . // american
‘(((2+)|(5(\\.3)+)))?(,9)?(6*))’ . // world
‘(e7+)?’ . // 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.

Читайте также:  Php show category name

Источник

ctype_digit

Проверяет, являются ли все символы в строке text цифровыми.

Список параметров

Замечание:

Если передано целое число ( int ) в диапазоне между -128 и 255 включительно, то оно будет обработано как ASCII-код одного символа (к отрицательным значениям будет прибавлено 256 для возможности представления символов из расширенного диапазона ASCII). Любое другое целое число будет обработано как строка, содержащая десятичные цифры этого числа.

Начиная с PHP 8.1.0, передача нестроковых аргументов устарела. В будущем аргумент будет интерпретироваться как строка вместо кода ASCII. В зависимости от предполагаемого поведения аргумент должен быть приведён к строке ( string ) или должен быть сделан явный вызов функции chr() .

Возвращаемые значения

Возвращает true , если каждый символ строки text является десятичной цифрой, либо false в противном случае. При вызове с пустой строкой результатом всегда будет false .

Примеры

Пример #1 Пример использования ctype_digit()

$strings = array( ‘1820.20’ , ‘10002’ , ‘wsl!12’ );
foreach ( $strings as $testcase ) if ( ctype_digit ( $testcase )) echo «Строка $testcase состоит только из цифр.\n» ;
> else echo «Строка $testcase не состоит только из цифр.\n» ;
>
>
?>

Результат выполнения данного примера:

Строка 1820.20 не состоит только из цифр. Строка 10002 состоит только из цифр. Строка wsl!12 не состоит только из цифр.

Пример #2 Пример использования ctype_digit() со сравнением строк и целых чисел

$numeric_string = ’42’ ;
$integer = 42 ;

ctype_digit ( $numeric_string ); // true
ctype_digit ( $integer ); // false (ASCII 42 — это символ *)

is_numeric ( $numeric_string ); // true
is_numeric ( $integer ); // true
?>

Смотрите также

  • ctype_alnum() — Проверяет наличие буквенно-цифровых символов
  • ctype_xdigit() — Проверяет наличие шестнадцатеричных цифр
  • is_numeric() — Проверяет, является ли переменная числом или строкой, содержащей число
  • is_int() — Проверяет, является ли переменная целым числом
  • is_string() — Проверяет, является ли переменная строкой

User Contributed Notes 14 notes

All basic PHP functions which i tried returned unexpected results. I would just like to check whether some variable only contains numbers. For example: when i spread my script to the public i cannot require users to only use numbers as string or as integer. For those situation i wrote my own function which handles all inconveniences of other functions and which is not depending on regular expressions. Some people strongly believe that regular functions slow down your script.

The reason to write this function:
1. is_numeric() accepts values like: +0123.45e6 (but you would expect it would not)
2. is_int() does not accept HTML form fields (like: 123) because they are treated as strings (like: «123»).
3. ctype_digit() excepts all numbers to be strings (like: «123») and does not validate real integers (like: 123).
4. Probably some functions would parse a boolean (like: true or false) as 0 or 1 and validate it in that manner.

My function only accepts numbers regardless whether they are in string or in integer format.
/**
* Check input for existing only of digits (numbers)
* @author Tim Boormans
* @param $digit
* @return bool
*/
function is_digit ( $digit ) if( is_int ( $digit )) return true ;
> elseif( is_string ( $digit )) return ctype_digit ( $digit );
> else // booleans, floats and others
return false ;
>
>
?>

Читайте также:  Java lang exception no runnable methods testing

Please note that ctype_digit() will say true for strings such as ‘00001’, which are not technically valid representations of integers, while saying false to strings such as ‘-1’, which are. It’s basically a faster version of the regex /^\d+$/. As the name says, it answers the question «does this string contain only digits» literally. It does not answer «is this a valid representation of an integer». If that’s what you want, use is_int(filter_var($val, FILTER_VALIDATE_INT)) instead.

I just wanted to clarify a flaw in the function is_digit() suggested by «info at directwebsolutions dot nl » ..
It returns true in case of negative integers and false in case of strings that contain negative integers .
example:
is_digit(-10); // returns ture
is_digit(‘-10’); // returns false

Interesting to note that you must pass a STRING to this function, other values won’t be typecasted (I figured it would even though above explicitly says string $text).

$val = 42 ; //Answer to life
$x = ctype_digit ( $val );
?>

Will return false, even though, when typecasted to string, it would be true.

$val = ’42’ ;
$x = ctype_digit ( $val );
?>

Returns True.

$val = 42 ;
$x = ctype_digit ((string) $val );
?>

Which will also return true, as it should.

ctype_digit() will treat all passed integers below 256 as character-codes. It returns true for 48 through 57 (ASCII ‘0’-‘9’) and false for the rest.

ctype_digit(5) -> false
ctype_digit(48) -> true
ctype_digit(255) -> false
ctype_digit(256) -> true

(Note: the PHP type must be an int; if you pass strings it works as expected)

Источник

is_numeric

Проверяет, является ли данная переменная числом. Строки, содержащие числа, состоят из необязательного знака, любого количества цифр, необязательной десятичной части и необязательной экспоненциальной части. Так, +0123.45e6 является верным числовым значением. Шестнадцатеричная (0xFF), двоичная (0b10100111001) и восьмеричная (0777) записи также допускаются, но только без знака, десятичной и экспоненциальной части.

Список параметров

Возвращаемые значения

Возвращает TRUE , если var является числом или строкой, содержащей число, в противном случае возвращается FALSE .

Примеры

Пример #1 Примеры использования is_numeric()

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

foreach ( $tests as $element ) if ( is_numeric ( $element )) echo «‘ < $element >‘ — число» , PHP_EOL ;
> else echo «‘ < $element >‘ — НЕ число» , PHP_EOL ;
>
>
?>

Результат выполнения данного примера:

'42' - число '1337' - число '1337' - число '1337' - число '1337' - число '1337' - число 'not numeric' - НЕ число 'Array' - НЕ число '9.1' - число

Смотрите также

  • ctype_digit() — Проверяет на наличие цифровых символов в строке
  • is_bool() — Проверяет, является ли переменная булевой
  • is_null() — Проверяет, является ли значение переменной равным NULL
  • is_float() — Проверяет, является ли переменная числом с плавающей точкой
  • is_int() — Проверяет, является ли переменная переменной целочисленного типа
  • is_string() — Проверяет, является ли переменная строкой
  • is_object() — Проверяет, является ли переменная объектом
  • is_array() — Определяет, является ли переменная массивом

Источник

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