您可以使用ctype_alpha檢查字母字符。
同樣,您可以使用ctype_digit來檢查數字字符。
is_numeric
- 檢測變量是否是一個數字或數字串
is_numeric()
例如:
<?php
$tests = array(
"42",
0b10100111001,
"not numeric",
array(),
9.1
);
foreach ($tests as $element) {
if (is_numeric($element)) {
echo "'{$element}' is numeric", PHP_EOL;
} else {
echo "'{$element}' is NOT numeric", PHP_EOL;
}
}
?>
上例將輸出:
'42' is numeric
'1337' is numeric
'not numeric' is NOT numeric
'Array' is NOT numeric
'9.1' is numeric
凡ctype_digit()
和is_numeric()
不同?
實例比較字符串與整數:
<?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
?>
是否有可能對整個字符串,而不是遍歷每個字符使用正則表達式? –
檢查http://stackoverflow.com/q/9721636/1169798和http://php.net/manual/en/function.is-numeric.php – Sirko
'is_numeric()'應該做檢查數字的技巧。 – tradyblix