如何在 php 中用除最后 4 位数字以外的星号替换手机号码



我正在尝试用星号替换手机号码,除了文本中的最后 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.

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

代码:(演示(

$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.',
)

我可以想象一些我的片段不会处理的边缘案例,但是每当您处理不遵守严格格式的电话号码时,您就会陷入挑战的兔子洞。

您可以直接从 $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);

旧但很有用...

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

最新更新