-
-
Save zu-min-g/e183cb5b0c9aa390a9a104da7749747f to your computer and use it in GitHub Desktop.
PHP の数値チェック
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$input = [ | |
1, | |
01, | |
0b1, | |
0x1, | |
-1, | |
'1', | |
'01', | |
'0b1', | |
'0x1', | |
'+1', | |
'-1', | |
0.9, | |
-0.9, | |
'0.9', | |
'+0.9', | |
'-0.9', | |
'0', | |
'+0', | |
'-0', | |
'1337e0', | |
'1.2e3', | |
'7E-10', | |
'1_234_567', | |
'1_234.567', | |
' 1', | |
"\n 1", | |
' 1 ', | |
'1,000', | |
'10.1', | |
'10000000000000000000001', | |
'0.10000000000000000000001', | |
'not numeric', | |
true, | |
false, | |
null, | |
[], | |
]; | |
$output = []; | |
foreach ($input as $item) { | |
ob_start(); | |
var_dump($item); | |
$dump = ob_get_contents(); | |
ob_end_clean(); | |
$output[] = [ | |
$item, | |
preg_replace('/$\n/', '', $dump), | |
is_int($item), | |
is_float($item), | |
is_numeric($item), | |
ctype_digit($item), | |
filter_var($item, FILTER_VALIDATE_INT) !== false, | |
filter_var($item, FILTER_VALIDATE_FLOAT) !== false, | |
// BC Math ドキュメントより。 10.1 とかは・・・? | |
is_string($item) && preg_match('/^[+-]?[0]*[1-9]*[.]?[0-9]*$/', $item) === 1, | |
// 自分の「数値」の感覚を正規表現にしたもの | |
is_string($item) && preg_match('/\A(-0(?=[.])|0|-?[1-9][0-9]*)([.][0-9]+)?\z/', $item) === 1, | |
]; | |
} | |
// JSON | |
// echo json_encode($output); | |
// CSV | |
$fp = fopen('php://output', 'w'); | |
foreach ($output as $line) { | |
array_shift($line); | |
fputcsv($fp, $line); | |
} | |
fclose($fp); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment