【问题标题】:How to replace the mobile number with stars except last 4 digits in php如何在php中用星号替换手机号码,除了最后4位数字
【发布时间】:2019-11-20 23:37:08
【问题描述】:

我正在尝试用除文本中最后 4 位数字之外的星号替换手机号码,并且该文本是动态的。

Eg. John's Mobile number is 8767484343 and he is from usa.
Eg. John's Mobile number is +918767484343 and he is from india.
Eg. Sunny's Mobile number is 08767484343 and he is from india.
Eg. Rahul's Mobile number is 1800-190-2312 and he is from india.



$dynamic_var = "John's Mobile number is 8767484343 and he is from usa.";

$number_extracted = preg_match_all('!\d+!', $dynamic_var , $contact_number);

// don't know what to do next
Result will be like 
Eg. John's Mobile number is ******4343 and he is from usa.
Eg. John's Mobile number is ******4343 and he is from india.
Eg. Sunny's Mobile number is ******4343 and he is from india.
Eg. Rahul's Mobile number is ******2312 and he is from india.

【问题讨论】:

  • 将号码视为手机号码的规则是什么?即我们可以有不同类型的号码手机号码、免费电话号码、固定电话号码等。
  • 联系电话可以是任何国家代码或没有国家代码。和免费电话号码,如 1800-120-9878,如果找到任何带 + 或 - 或没有这些数字的数字,它应该替换除最后四个之外的整个数字。
  • 它工作正常,但将最后四位数字替换为星号。我想将除最后四位之外的所有手机号码替换为星号。
  • 好的,试试preg_replace_callback('~\+?\d+(?:[-\s]*\d)*(?=(?:[-\s]*\d){4}(?!-?\d))~', function($m) { return preg_replace('~\d~', '*', $m[0]); }, $dynamic_var)
  • 但它没有从其他输入中替换 + 和 -

标签: php regex replace


【解决方案1】:

根据我对您的示例输入和所需输出的了解,您不需要preg_replace_callback() 的开销。可变长度前瞻将允许您一次用星号替换一个字符,只要它后跟 4 个或更多数字或连字符即可。

代码:(Demo)

$inputs = [
    "John's Mobile number is 8767484343 and he is from usa.",
    "John's Mobile number is +918767484343 and he is from india.",
    "Sunny's Mobile number is 08767484343 and he is from Pimpri-Chinchwad, india.",
    "Rahul's Mobile number is 1800-190-2312 and he is from india."
];

var_export(preg_replace('~[+\d-](?=[\d-]{4})~', '*', $inputs));

输出:

array (
  0 => 'John\'s Mobile number is ******4343 and he is from usa.',
  1 => 'John\'s Mobile number is *********4343 and he is from india.',
  2 => 'Sunny\'s Mobile number is *******4343 and he is from Pimpri-Chinchwad, india.',
  3 => 'Rahul\'s Mobile number is *********2312 and he is from india.',
)

我可以设想一些我的 sn-p 无法处理的边缘案例,但每当您处理不符合严格格式的电话号码时,您就会陷入困境。

【讨论】:

  • @Rohit 从我之前的模式中删除逗号。我更新了。
【解决方案2】:

您可以像这样直接从您的 $dynamic_var 中实现这一点:

$dynamic_var = "John's Mobile number is 8767484343 and he is from usa.";
$result = preg_replace_callback('/(?<=\s)(\d|-|\+)+(?=\d{4}\s)/U', function($matches) {
    return str_repeat("*", strlen($matches[0]));
}, $dynamic_var);

【讨论】:

    【解决方案3】:

    旧但有用...

    <?php
        echo str_repeat('*', strlen("123456789") - 4) . substr("123456789", -4);
    ?>
    

    【讨论】:

      猜你喜欢
      • 2021-08-07
      • 1970-01-01
      • 1970-01-01
      • 2020-12-28
      • 2012-07-11
      • 1970-01-01
      • 1970-01-01
      • 2021-05-06
      • 2013-02-23
      相关资源
      最近更新 更多