Reputation:
I want to replace equal number of unmatched characters with *
. Like as I've string
[email protected]
should be replace into
x*********s@x**s.com
Right now just for work around I'm using the following regex
^(\w).*?(.@.).*?(.\.\w+)
So using that followed regex along with preg_replace
like as
echo preg_replace('/^(\w).*?(.@).*?(\.\w+)/', "$1****$2****$3", "[email protected]");
which result into
x****s@x****s.com
but what I want to achieve over here is
x*********s@x**s.com
Upvotes: 2
Views: 232
Reputation: 6394
Another try, without explode
:
<?php
$email="[email protected]" ;
$arobase_pos = strpos($email,"@"); // first occurence of "@"
$dot_pos = strrpos($email,"."); // last occurence of ".""
// from 2 to post(@) -1
$email = substr_replace($email, str_repeat ("*", $arobase_pos - 2), 1, $arobase_pos - 2);
// from pos(@)+2 to pos(.)-1
$email = substr_replace($email, str_repeat ("*", $dot_pos-1-$arobase_pos-2), $arobase_pos + 2, $dot_pos-1-$arobase_pos-2);
// Display
echo $email;
?>
Upvotes: 0
Reputation: 10951
Also you can use preg_replace_callback
function
function callbackFunction($m) {
return $m[1].(str_repeat('*', strlen($m[2]))).$m[3].(str_repeat('*', strlen($m[4]))).$m[5];
}
$pattern = '|^(\\w)(.*?)(.@.)(.*?)(.\\.\\w+)|';
$subject = '[email protected]';
print_r( preg_replace_callback($pattern, 'callbackFunction', $subject, -1 ) );
Upvotes: 0
Reputation: 174706
I would use (*SKIP)(*F)
preg_replace('~(?:^.|.@.|.\.\w+$)(*SKIP)(*F)|.~', '*', $str);
(?:^.|.@.|.\.\w+$)
(*SKIP)(*F)
|
OR|
will match all the characters other than the skipped ones.Upvotes: 3
Reputation: 10714
Not using preg_replace, just to give you an idea, my code is not optimized ! (I know)
$str = '[email protected]';
$buff = explode('@', $str);
$buff2 = explode('.', $buff[1]);
$part1 = $buff[0][0] . str_repeat('*', strlen($buff[0]) - 2) . $buff[0][strlen($buff[0]) - 1];
$part2 = $buff[1][0] . str_repeat('*', strlen($buff2[0]) - 2) . $buff2[0][strlen($buff2[0]) - 1];
echo $part1 .'@'. $part2 .'.'. $buff2[1];
But it works.
Upvotes: 0