I am trying to replace the mobile number with stars except last 4 digits within a text and the text is dynamic.
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.
You can achieve that directly from your $dynamic_var like this for example:
$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);
From what I see of your sample input and your desired output, you don't need the overhead of preg_replace_callback()
. A variable length lookahead will allow you to replace one character at a time with an asterisk so long as it is followed by 4 or more digits or hyhpens.
Code: ( 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));
Output:
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.',
)
I could dream up some fringe cases that will not be handled by my snippet, but whenever you are dealing with phone number that aren't obeying a strict format, you are going down a rabbit hole of challenges.
Old but useful...
<?php
echo str_repeat('*', strlen("123456789") - 4) . substr("123456789", -4);
?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.