我有一个字符串值从数据库
我需要检查这个值是整数还是字符串。
我试过is_int
和is_numeric
,但这两个都不是我需要的。
is_int
总是返回false,如果值的类型是字符串,而is_numeric
返回true,如果我的值包含数字。
我使用的是preg_match('/^d+$/',$value)
,而且,在这种情况下,我正在寻找一个简单的解决方案。
$stringIsAnInteger = ctype_digit($string);
ctyped_digit()
您可以使用ctype_digit()
-检查数字字符。检查所提供的字符串(text)中的所有字符是否都是数字。
<?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";
}
}
?>
上面将输出
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.
示例2 <?php
$numeric_string = '42';
$integer = 42;
ctype_digit($numeric_string); // true
ctype_digit($integer); // false (ASCII 42 is the * character)
is_numeric($numeric_string); // true
is_numeric($integer); // true
?>
我发现你的方式是最好的。
我看不出一个简单的正则表达式有什么复杂的,所以,在你的位置上,我不会寻找更简单的。
说到复杂性,不要只局限于调用者的代码。
它可以像单个函数调用一样短。但是你不能确定底层的代码,它可能非常复杂,而且——重要的是——有一些问题,就像这里提到的每个函数一样。
而您自己的解决方案既简单又健壮。
更新:所有关于"在可以使用简单字符串函数来提高性能的地方不要使用regexp之类的注释"都直接来自上个世纪。
- 这并不意味着"即使没有字符串函数适合你,也不要使用regexp"
- 现在是21世纪了,计算机的速度非常快,尤其是在文本解析这样简单的事情上。这样一个简单的regexp将永远不会成为应用程序的瓶颈。因此,就性能优化而言,没有理由更喜欢字符串函数而不是regexp。在现实生活中的应用程序,你永远不会注意到(或测量)任何差异。