【发布时间】:2026-01-18 06:55:01
【问题描述】:
我想获取整数值的长度以在 PHP 中进行验证。 例子: 手机号码只能是 10 个整数值。不得超过 10 或小于 10,也不应包含字母字符。
如何验证?
【问题讨论】:
我想获取整数值的长度以在 PHP 中进行验证。 例子: 手机号码只能是 10 个整数值。不得超过 10 或小于 10,也不应包含字母字符。
如何验证?
【问题讨论】:
$num_length = strlen((string)$num);
if($num_length == 10) {
// Pass
} else {
// Fail
}
【讨论】:
$num_length = strlen((string)abs($num))
if (preg_match('/^\d{10}$/', $string)) {
// pass
} else {
// fail
}
【讨论】:
这几乎适用于所有情况(零除外)并且可以轻松地用其他语言进行编码:
$length = ceil(log10(abs($number) + 1)
【讨论】:
在我看来,最好的方法是:
$length = ceil(log10($number))
四舍五入的十进制对数等于数字的长度。
【讨论】:
如果您使用的是网络表单,请确保将文本输入限制为仅包含 10 个字符,以增加一些可访问性(用户不想输入错误,提交,获取有关错误的对话框,修复它,再次提交,等等)
【讨论】:
在循环中使用intval函数, 看这个例子
<?php
$value = 16432;
$length=0;
while($value!=0) {
$value = intval($value/10);
$length++
}
echo "Length of Integer:- ".$length;
?>
【讨论】:
$input = "03432 123-456"; // A mobile number (this would fail)
$number = preg_replace("/^\d/", "", $number);
$length = strlen((string) $number);
if ($number == $input && $length == 10) {
// Pass
} else {
// Fail
}
【讨论】:
如果您正在评估手机号码(电话号码),那么我建议您不要使用 int 作为您选择的数据类型。请改用字符串,因为我无法预见您要如何或为什么要使用这些数字进行数学运算。作为最佳实践,当您想要/需要进行数学运算时,请使用 int、floats 等。不使用时使用字符串。
【讨论】:
从你的问题,“你想得到一个整数的长度,输入将不接受字母数字数据,整数的长度不能超过 10。如果这是你的意思;在我自己看来,这是实现这一目标的最佳方法:"
<?php
$int = 1234567890; //The integer variable
//Check if the variable $int is an integer:
if (!filter_var($int, FILTER_VALIDATE_INT)) {
echo "Only integer values are required!";
exit();
} else {
// Convert the integer to array
$int_array = array_map('intval', str_split($int));
//get the lenght of the array
$int_lenght = count($int_array);
}
//Check to make sure the lenght of the int does not exceed or less than10
if ($int_lenght != 10) {
echo "Only 10 digit numbers are allow!";
exit();
} else {
echo $int. " is an integer and its lenght is exactly " . $int_lenght;
//Then proceed with your code
}
//This will result to: 1234556789 is an integer and its lenght is exactly 10
?>
【讨论】: