繁体   English   中英

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

[英]How to replace the mobile number with stars except last 4 digits in php

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

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

从我看到的示例输入和所需的输出来看,您不需要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.',
)

我可以想象出一些我的代码片段无法处理的边缘案例,但是每当您处理不遵守严格格式的电话号码时,您就会陷入困境。

旧但有用...

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM