我正在尝试用星号替换手机号码,但文本中的最后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.
答案 0 :(得分:1)
例如,您可以直接从$ 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);
答案 1 :(得分: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.',
)
我可以幻想一些我的代码片段无法处理的附带情况,但是每当您处理不遵循严格格式的电话号码时,您都会遇到很多难题。
答案 2 :(得分:1)
老但有用...
<?php
echo str_repeat('*', strlen("123456789") - 4) . substr("123456789", -4);
?>