Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a string contains an integer

Tags:

validation

php

Do you know of a function that can check if a string contains an integer?

Here's how I'd expect it to work:

holds_int("23") // should return true.   holds_int("2.3") // should return false.   holds_int("qwe") // should return false. 
like image 914
Emanuil Rusev Avatar asked Jul 31 '10 09:07

Emanuil Rusev


People also ask

How do you check if a string contains an integer in C?

Using built-in method isdigit(), each character of string is checked. If the string character is a number, it will print that string contains int. If string contains character or alphabet, it will print that string does not contain int.

How do you check if a string contains integers in Python?

Python String isnumeric() Method The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False. Exponents, like ² and ¾ are also considered to be numeric values. "-1" and "1.5" are NOT considered numeric values, because all the characters in the string must be numeric, and the - and the .


1 Answers

if((string)(int)$var == $var) {     echo 'var is an integer or a string representation of an integer'; } 

Example results:

var_dump( test(1)             ); // TRUE var_dump( test('1')           ); // TRUE var_dump( test('1.0')         ); // TRUE var_dump( test('1.1')         ); // false var_dump( test('0xFF')        ); // false var_dump( test('0123')        ); // TRUE var_dump( test('01090')       ); // TRUE var_dump( test('-1000000')    ); // TRUE var_dump( test('+1000000')    ); // TRUE var_dump( test('2147483648')  ); // false var_dump( test('-2147483649') ); // false 

See Gordon's answer below for how this would behave differently if === were used for comparison instead of ==.

like image 181
Jhong Avatar answered Sep 22 '22 19:09

Jhong