PHP 正则表达式 - 如何对 preg_replace 数字反向引用执行 str_replace?

PHP Regex - How to do str_replace on preg_replace numeric backreferences?

我有以下 PHP 正则表达式代码,用“[已删除的电子邮件]”替换字符串替换所有电子邮件;效果很好:

$pattern = "/[^@\s]*@[^@\s]*\.[^@\s]*/"; 
$replacement = "[removed email]";
$body_highlighted = preg_replace($pattern, $replacement, $body_highlighted);

但是,电子邮件替换策略发生了变化,现在我需要实际显示电子邮件但替换其中的某些部分。我想像这样在数字反向引用上使用 str_replace,但它不起作用。

$pattern = "/[^@\s]*@[^@\s]*\.[^@\s]*/"; 
$email_part = "[=14=]";
$replacement = str_replace('a','b', $email_part); // replace all letter A with B in each email
$body_highlighted = preg_replace($pattern, $replacement, $body_highlighted);

知道我做错了什么吗?

您在实际字符串 [=13=] 上使用 str_replace 而不是它引用的反向引用,这就是它不起作用的原因。

您想在执行 preg_replace 的同时执行 str_replace,因此您可以使用 preg_replace_callback 使用回调函数获取“电子邮件部分”并执行在正则表达式替换期间对其进行字符串操作。

要提取电子邮件的第一部分(“@”之前)并进行更改:

$pattern = "/([^@\s]*)(@[^@\s]*\.[^@\s]*)/"; 
$body_highlighted = preg_replace_callback($pattern, 'change_email', $body_highlighted);

/* str_replace the first matching part on the email */
function change_email($matches){
  return str_replace('a','b', $matches[1]).$matches[2];
}

如果您使用它,例如:
$body_highlighted = "My email is aaaazz@gmail.com";
结果:My email is bbbbzz@gmail.com

请注意 $pattern 中正则表达式的更改,将电子邮件分为两部分 - 在 @ 之前,部分包括 @ 和域名。这些在回调函数中作为 $matches[1]$matches[2].

访问

如果要访问电子邮件地址的域部分(在@之后):

您可以将电子邮件分成 3 部分(在 @ 之前、@@ 之后的所有部分)您可以使用以下内容:

$pattern = "/([^@\s]*)(@)([^@\s]*\.[^@\s]*)/"; 
$body_highlighted = preg_replace_callback($pattern, 'change_email', $body_highlighted);

function change_email($matches){
  return str_replace('a','b', $matches[1]).$matches[2].str_replace('y','z', $matches[3]);
}