我有以下代码:
<?php
function s2int($pinned_id) {
$action="aaa";
if ( $action && is_numeric($pinned_id) && (float)$pinned_id==(int)$pinned_id) {
/**
* @param [string] $action is setted
* @param [int/string as int] $pinned_id is setted
*/
echo "-chekpoint- $pinned_id\n";
$pinned_id = (int)$pinned_id;
}
else { echo "-passpoint- $pinned_id\n";}
return $pinned_id;
}
echo s2int("000010")."\n";
echo s2int(10.00001)."\n";
echo s2int(10)."\n";
echo s2int("10")."\n";
echo s2int("0")."\n";
echo s2int("a")."\n";
echo s2int("a10")."\n";
echo s2int("10a")."\n";
echo s2int("0x1A")."\n";
echo s2int("-100")."\n";
输出:
-chekpoint- 000010
10
-passpoint- 10.00001
10.00001
-chekpoint- 10
10
-chekpoint- 10
10
-chekpoint- 0
0
-passpoint- a
a
-passpoint- a10
a10
-passpoint- 10a
10a
-chekpoint- 0x1A
0
-chekpoint- -100
-100
预期输出:
-chekpoint- 000010
10
-passpoint- 10.00001
10.00001
-chekpoint- 10
10
-chekpoint- 10
10
-chekpoint- 0
0
-passpoint- a
a
-passpoint- a10
a10
-passpoint- 10a
10a
-passpoint- 0x1A
0x1A
-chekpoint- -100
-100
让 s2int 返回正确的 (int) 变量并在变量无法转换为 (int) 时采取行动的最佳做法是什么(如果输入是十六进制,您会看到结果意外?
最佳答案
我会使用 filter_var()
为此:
if (false === ($x = filter_var($pinned_id, FILTER_VALIDATE_INT))) {
echo "Could not convert $pinned_id to an integer";
}
// $x is an integer
000010
的大小写不明确,因为它也可能表示八进制;但是如果你想要一个 10 基数,你必须去除所有前导零:
$num = preg_replace('/^0+(\d+)/', '\\1', $pinned_id);
if (false === ($x = filter_var($num, FILTER_VALIDATE_INT))) {
echo "Could not convert $pinned_id to an integer";
}
// $x is an integer
如果你也想允许十六进制:
if (false === ($x = filter_var($num, FILTER_VALIDATE_INT, array(
'flags' => FILTER_FLAG_ALLOW_HEX,
))) {
echo "Could not convert $pinned_id to an integer";
}
// $x is an integer
编辑
你也可以选择 preg_match()
路线:
function s2int($pinned_id) {
echo "/$pinned_id/ ";
if (!preg_match('/^-?\d+$/', $pinned_id)) {
echo "Could not convert $pinned_id to an integer";
return false;
}
return (int)$pinned_id;
}
出于某种原因,这不会在键盘上运行,但它应该在任何其他系统上运行
关于php - 使字符串为 int 并检查字符串是否为 int 的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12738597/