验证数值但排除十六进制或sci表示法

时间:2014-11-07 19:05:00

标签: php regex validation hex preg-match

我曾经依赖is_numeric()来确保从用户传递的数据是数字的。我最近发现用户也可以传递数据0xFF(hexdec = 255)。

我想禁止任何不是整数的东西(而不是十六进制表示)。

这是我迄今为止所尝试的内容。

$i_haxors_u = $_GET['id'];

$regex = '/[0-9]*/';
if (!empty($i_haxors_u) && !preg_match($regex, $i_haxors_u))
 {
   echo '<p>Invalid $i_haxors_u ' . strip_tags($i_haxors_u);
 } else { 
   echo '<p>$i_haxors_u is numeric... maybe.';
 }

这仍然是0xFF这样的值。如何仅允许非十六进制数字?


更新2014年11月12日。

请注意,selected answer适用于通过GET传递的数据,但如果将变量设置为十六进制值则无效。

$x = 0xFF;
if (is_numeric($x))
{
    echo "<p>$x is a number.";
} else {
    echo "<p>$x is not a number.";
}

if (preg_match('/^[\d]+$/',$x))
{
    echo "<p>$x is a number.";
} else {
    echo "<p>$x is not a number.";
}

$x = '0xFF';
if (is_numeric($x))
{
    echo "<p>$x is a number.";
} else {
    echo "<p>$x is not a number.";
}

if (preg_match('/^[\d]+$/',$x))
{
    echo "<p>$x is a number.";
} else {
    echo "<p>$x is not a number.";
}

打印

255 is a number.

255 is a number.

0xFF is a number.

0xFF is not a number.

3 个答案:

答案 0 :(得分:2)

在正则表达式中使用匹配非数字:$ regex =&#39; / \ D /&#39 ;; 当确认输入中没有非数字时,假设失败并通过。

以下代码在id = 7时成功,在id = 7.2,7.2x,ffff,0xff,-1

上给出失败
$id = $_GET['id'];

//assuming failure:
$valid = false;

if (!preg_match('/\D/',$id)) { $valid = true; } //fail if containing non-digit


if ($valid) {
echo "$id provided is valid";
}
else {
echo "$id provided is not valid";
}

答案 1 :(得分:1)

您需要使用锚点并使用+量词来仅允许整数:

$regex = '/^\d+$/';

使用+量词还可以让您取消!empty($i_haxors_u)条件,因为\d+会强制执行1位或更多位数。

答案 2 :(得分:1)

这只是因为你必须测试所有数字:

$regex = '/^[0-9]+$/';

无需用+

测试空