How to convert a String to Integer and test it?
I've a problem. I'm scrapping a txt file and extracting an ID. The problem is that the data is not consistent and I hav开发者_如何学Goe to evaluate the data.
Here is some code:
$a = "34";
$b = " 45";
$c = "ddd556z";
if ( ) {
echo "INTEGER";
} else{
echo "STRING";
}
I need test if the values $a, $b or $c are Integers. What is the best way of doing this? I have tested to "trim" and the use "is_int" but is not working as expected.
Can someone give me some clues?
The example below will work even if your "int" is a string $a = "number";
is_numeric()
or
preg_match( '/^-?[0-9]+$/' , $var ) // negative number © Piskvor
or
intval($var) == $var
or (same as last)
(int) $var == $var
http://www.php.net/manual/en/function.ctype-digit.php
<?php
$strings = array('1820.20', '10002', 'wsl!12');
foreach ($strings as $testcase) {
if (ctype_digit($testcase)) {
echo "The string $testcase consists of all digits.\n";
} else {
echo "The string $testcase does not consist of all digits.\n";
}
}
// will output
//The string 1820.20 does not consist of all digits.
//The string 10002 consists of all digits.
//The string wsl!12 does not consist of all digits.
<?
$a = 34;
if (is_int($a)) {
echo "is integer";
} else {
echo "is not an integer";
}
?>
$a="34";
will not validate as int ;)
精彩评论