我想用*
替换相等数量的不匹配字符。比如string
xyzdsdasdas@xyss.com
应替换为
x*********s@x**s.com
现在只是为了工作,我使用以下regex
^('w).*?(.@.).*?(.'.'w+)
因此使用后面的regex和preg_replace
,如
echo preg_replace('/^('w).*?(.@).*?('.'w+)/', "$1****$2****$3", "xyzdsdasdas@xyss.com");
生成
x****s@x****s.com
但是我想在这里实现的是
x*********s@x**s.com
我会用(*SKIP)(*F)
preg_replace('~(?:^.|.@.|.'.'w+$)(*SKIP)(*F)|.~', '*', $str);
演示- 首先匹配所有你不想要的字符。即
(?:^.|.@.|.'.'w+$)
现在,使用 -
|
或 - 现在
|
后面的点将匹配除跳过的字符以外的所有字符。
(*SKIP)(*F)
跳过这些匹配不使用preg_replace,只是给你一个想法,我的代码没有优化!(我知道)
$str = 'xyzdsdasdas@xyss.com';
$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];
但是它成功了
也可以使用preg_replace_callback
函数
function callbackFunction($m) {
return $m[1].(str_repeat('*', strlen($m[2]))).$m[3].(str_repeat('*', strlen($m[4]))).$m[5];
}
$pattern = '|^(''w)(.*?)(.@.)(.*?)(.''.''w+)|';
$subject = 'xyzdsdasdas@xyss.com';
print_r( preg_replace_callback($pattern, 'callbackFunction', $subject, -1 ) );
再试一次,没有explode
:
<?php
$email="blablabla@truc.com" ;
$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;
?>