我想从句子中替换号码和电子邮件。
示例
$ message ="嗨,这是约翰,我的个人号码是1213456789,我的电子邮件地址是john@gmail.com"。
输出:
嗨,这是约翰,我的个人号码是1213456789,我的电子邮件地址是john@gmail.com
我希望输出像这样:
输出:
嗨,这是约翰,我的个人号码是XXXXXXX789,我的电子邮件地址是XXXX@gmail.com
但我现在这样:
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX@gmail.com
我现在正在使用的功能
function numbers1($str)
{
if(($until = strpos($str, '@')) !== false)
{
$str = str_repeat('X', $until) . substr($str, $until);
}
}
提前致谢。
答案 0 :(得分:2)
尝试preg_replace()
$str = "Hi this is john, my personal no is 1213456789 and my email address is john@gmail.com";
$replacements[1] = 'X';
$replacements[0] = 'XXXX@';
echo preg_replace(array('/[0-6]/', '/[ a-z]{0,4}+@/'), $replacements, $str);
输出: - Hi this is john, my personal no is XXXXXXX789 and my email address is XXXX@gmail.com
答案 1 :(得分:1)
$message = "Hi this is john, my personal no is 1213456789 and my email address is john@gmail.com";
$arr = explode(" ", $message);
foreach($arr as $key=>$val)
{
if(!preg_match ("/[^0-9]/", $val))
{
$val_new = "XXXXXXX".substr($val, -3);
$arr[$key] = $val_new;
}
else if(strpos($val, "@")>0)
{
$arr_email = explode("@", $val);
$arr_email[0] = "XXXX";
$val_new = implode("@", $arr_email);
$arr[$key] = $val_new;
}
}
$new_msg = implode(" ", $arr);
echo $new_msg;
更新2:
$message = "Hi this is john, my personal no is 1213456789 and my email address is john@gmail.com";
$arr = explode(" ", $message);
foreach($arr as $key=>$val)
{
if(!preg_match ("/[^0-9]/", $val))
{
$val_new = "XXXXXXX".substr($val, -3);
$arr[$key] = $val_new;
}
else if(preg_match ("/^[a-z0-9_\+-]+(\.[a-z0-9_\+-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,4})$/", $val))
{
$arr_email = explode("@", $val);
$arr_email[0] = "XXXX";
$val_new = implode("@", $arr_email);
$arr[$key] = $val_new;
}
}
$new_msg = implode(" ", $arr);
echo $new_msg;
答案 2 :(得分:1)
您正在询问如何使用jQuery执行此操作,但您的示例代码是用PHP编写的。我也会用PHP片段回答你的问题。
你的功能无法正常工作的原因是因为你要从字符串的开头到找到第一个'@'的位置替换几乎所有内容。然后,您将添加与字符一样多的“X”,直到该位置,然后是字符串的其余部分。更复杂的是,如果在您的字符串中找到两个或多个电子邮件地址,这将无效。
这应该做。您可能需要调整电话号码和电子邮件地址的正则表达式:
$message = "Hi this is john, my personal no is 1213456789 and my email address is john@gmail.com";
// get all phone numbers
preg_match('/\d{3,}/s', $message, $phones);
// get all email addresses
preg_match('/[a-z.-]+@[a-z.-]+/s', $message, $emails);
foreach ($phones as $phone)
{
$message = str_replace($phone, str_repeat('X', strlen($phone) - 3) . substr($phone, -3), $message);
}
foreach ($emails as $email)
{
$parts = explode('@', $email);
$message = str_replace($email, str_repeat('X', strlen($parts[0])) . '@' . $parts[1], $message);
}
// Hi this is john, my personal no is XXXXXXX789 and my email address is XXXX@gmail.com
echo $message;