regex 如何在php中用星号替换移动的号码,除了最后4位数字

edqdpe6u  于 2023-01-31  发布在  PHP
关注(0)|答案(3)|浏览(117)

我正试图取代手机号码与星级除了最后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.
62o28rlo

62o28rlo1#

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

我可以想象一些我的代码片段无法处理的边缘情况,但无论何时,当您处理不遵守严格格式的电话号码时,您都将陷入一个充满挑战的兔子洞。

pengsaosao

pengsaosao2#

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

c8ib6hqw3#

古老但有用...

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

相关问题