PHP中如何获取整数的长度?

发布于 2024-09-28 18:49:30 字数 94 浏览 4 评论 0原文

我想获取整数值的长度以在 PHP 中进行验证。 例子: 手机号码只能是 10 个整数值。不能多于10个,也不能少于10个,且不能包含字母。

我如何验证这一点?

I want to get the length of integer values for validation in PHP.
Example:
Mobile numbers should be only 10 integer values. It should not be more than 10 or less than 10 and also it should not be included of alphabetic characters.

How can I validate this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

天气好吗我好吗 2024-10-05 18:49:30
$num_length = strlen((string)$num);
if($num_length == 10) {
    // Pass
} else {
    // Fail
}
$num_length = strlen((string)$num);
if($num_length == 10) {
    // Pass
} else {
    // Fail
}
安静 2024-10-05 18:49:30
if (preg_match('/^\d{10}$/', $string)) {
  // pass
} else {
  // fail
}
if (preg_match('/^\d{10}$/', $string)) {
  // pass
} else {
  // fail
}
羅雙樹 2024-10-05 18:49:30

这适用于几乎所有情况(除了零)并且可以轻松地用其他语言进行编码:

$length = ceil(log10(abs($number) + 1));

This will work for almost all cases (except zero) and easily coded in other languages:

$length = ceil(log10(abs($number) + 1));
懒的傷心 2024-10-05 18:49:30

在我看来,最好的方法是:

$length = ceil(log10($number))

小数对数向上舍入等于数字的长度。

In my opinion, the best way is:

$length = ceil(log10($number))

A decimal logarithm rounded up is equal to length of a number.

游魂 2024-10-05 18:49:30

如果您使用的是 Web 表单,请确保将文本输入限制为仅包含 10 个字符,并添加一些辅助功能(用户不想输入错误,提交,获得有关错误的对话框,修复它,提交再次,等等)

If you are using a web form, make sure you limit the text input to only hold 10 characters as well to add some accessibility (users don't want to input it wrong, submit, get a dialog about their mistake, fix it, submit again, etc.)

任性一次 2024-10-05 18:49:30

在循环中使用 intval 函数,
看这个例子

<?php
  $value = 16432;
  $length=0;
  while($value!=0) {
   $value = intval($value/10);
   $length++
  }
  echo "Length of Integer:- ".$length;
 ?>

Use intval function in loop,
See this example

<?php
  $value = 16432;
  $length=0;
  while($value!=0) {
   $value = intval($value/10);
   $length++
  }
  echo "Length of Integer:- ".$length;
 ?>
寄离 2024-10-05 18:49:30
$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
}
$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
}
吻风 2024-10-05 18:49:30

如果您正在评估手机号码(电话号码),那么我建议不要使用 int 作为您选择的数据类型。请使用字符串,因为我无法预见您想要如何或为何使用这些数字进行数学运算。作为最佳实践,当您想要/需要进行数学运算时,请使用 int、float 等。不使用时使用字符串。

If you are evaluating mobile numbers (phone numbers) then I would recommend not using an int as your chosen data type. Use a string instead because I cannot forsee how or why you would want to do math with these numbers. As a best practice, use int, floats, etc, when you want/need to do math. Use strings when you don't.

殤城〤 2024-10-05 18:49:30

从你的问题来看,“你想获得整数的长度,输入不会接受字母数字数据,并且整数的长度不能超过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

?>

From your question, "You want to get the lenght of an integer, the input will not accept alpha numeric data and the lenght of the integer cannot exceed 10. If this is what you mean; In my own opinion, this is the best way to achieve that:"

<?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

?>
空城仅有旧梦在 2024-10-05 18:49:30

通过使用 Webmozart Assert 的断言库,我们可以使用它们的内置方法来验证输入。

  • 使用 integerish() 验证值是否转换为整数
  • 使用 length() 验证字符串是否具有一定数量的字符

示例

Assert::integerish($input);
Assert::length((string) $input, 10); // expects string, so we type cast to string

由于 Assert 类中的所有断言如果失败都会抛出 Webmozart\Assert\InvalidArgumentException,因此我们可以捕获它并向用户传达明确的消息。

示例

try {
    Assert::integerish($input);
    Assert::length((string) $input, 10);
} catch (InvalidArgumentException) {
    throw new Exception('Please enter a valid phone number');
}

作为额外的,甚至可以检查该值是否不是非负整数。

示例

try {
    Assert::natural($input);
} catch (InvalidArgumentException) {
    throw new Exception('Please enter a valid phone number');
}

我希望它有帮助

By using the assertion library of Webmozart Assert we can use their build-in methods to validate the input.

  • Use integerish() to validate that a value casts to an integer
  • Use length() to validate that a string has a certain number of characters

Example

Assert::integerish($input);
Assert::length((string) $input, 10); // expects string, so we type cast to string

As all assertions in the Assert class throw an Webmozart\Assert\InvalidArgumentException if they fail, we can catch it and communicate a clear message to the user.

Example

try {
    Assert::integerish($input);
    Assert::length((string) $input, 10);
} catch (InvalidArgumentException) {
    throw new Exception('Please enter a valid phone number');
}

As an extra, it's even possible to check if the value is not a non-negative integer.

Example

try {
    Assert::natural($input);
} catch (InvalidArgumentException) {
    throw new Exception('Please enter a valid phone number');
}

I hope it helps ????

弥枳 2024-10-05 18:49:30

2或3步中的一点优化答案取决于我们是否允许负值

if(is_int($number)
&& strlen((string)$number) == 10)
{
   // 1 000 000 000 Executions take from 00:00:00.153200 to 00:00:00.173900
   //Code
}

注意,最多允许负数9个数字,例如-999999999

因此,如果我们需要跳过负数,我们需要第三次比较

if(is_int($number)
&& $number >= 0
&& strlen((string)$number) == 10)
{
   // 1 000 000 000 Executions take from 00:00:00.153200
   // to 00:00:00.173900 over 20 tests
}

最后一种情况是我们想要从-1 000 000 000到1 000 000 000


if(is_int($number)
&& $number >= 0
&& strlen(str_replace('-', '', (string)$number)) == 10)
{
   // 1 000 000 000 Executions take from 00:00:00.153200
   // to 00:00:00.173900 over 20 tests
}

用于比较
第一个使用正则表达式的 naswer

if (preg_match('/^\d{10}$/', $number)) {
  // Fastest test with 00:00:00.246200
}

** 在 PHP 8.0.12 上测试
** XAMPP 3.3.0
** 锐龙 7 2700
** MSI Radeon RX 5700 8G

测试如下

$function = function($number)
{
   if(is_int($number)
   && $number >= 0
   && strlen((string)$number) == 10)
   {
      return true;
   }
}

$number = 1000000000;

$startTime = DateTime::createFromFormat('U.u', microtime(true);

for($i = 0; $i < 1000000000; $i++)
{
   call_user_func_array($function, $args);
}

$endTime = DateTime::createFromFormat('U.u', microtime(true);

echo $endTime->diff($startTime)->format('%H:%I:%S.%F');

A bit optimazed answer in 2 or 3 steps depends if we allow negative value

if(is_int($number)
&& strlen((string)$number) == 10)
{
   // 1 000 000 000 Executions take from 00:00:00.153200 to 00:00:00.173900
   //Code
}

Note that will allow negative up to 9 numbers like -999999999

So if we need skip negatives we need 3rd comparision

if(is_int($number)
&& $number >= 0
&& strlen((string)$number) == 10)
{
   // 1 000 000 000 Executions take from 00:00:00.153200
   // to 00:00:00.173900 over 20 tests
}

Last case when we want from -1 000 000 000 to 1 000 000 000


if(is_int($number)
&& $number >= 0
&& strlen(str_replace('-', '', (string)$number)) == 10)
{
   // 1 000 000 000 Executions take from 00:00:00.153200
   // to 00:00:00.173900 over 20 tests
}

For compare
First naswer with regex

if (preg_match('/^\d{10}$/', $number)) {
  // Fastest test with 00:00:00.246200
}

** Tested at PHP 8.0.12
** XAMPP 3.3.0
** Ryzen 7 2700
** MSI Radeon RX 5700 8G

Tested like

$function = function($number)
{
   if(is_int($number)
   && $number >= 0
   && strlen((string)$number) == 10)
   {
      return true;
   }
}

$number = 1000000000;

$startTime = DateTime::createFromFormat('U.u', microtime(true);

for($i = 0; $i < 1000000000; $i++)
{
   call_user_func_array($function, $args);
}

$endTime = DateTime::createFromFormat('U.u', microtime(true);

echo $endTime->diff($startTime)->format('%H:%I:%S.%F');

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文