PHP正则表达式-如何在preg_替换数值反向引用时进行str_替换?

PHP正则表达式-如何在preg_替换数值反向引用时进行str_替换?,php,regex,preg-replace,Php,Regex,Preg Replace,我有以下PHP正则表达式代码,用“[删除的电子邮件]”替换字符串替换所有电子邮件;而且效果很好: $pattern = "/[^@\s]*@[^@\s]*\.[^@\s]*/"; $replacement = "[removed email]"; $body_highlighted = preg_replace($pattern, $replacement, $body_highlighted); 然而,电子邮件替换策略改变了,现在我需要实际显示电子邮

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

$pattern = "/[^@\s]*@[^@\s]*\.[^@\s]*/"; 
$replacement = "[removed email]";
$body_highlighted = preg_replace($pattern, $replacement, $body_highlighted);
然而,电子邮件替换策略改变了,现在我需要实际显示电子邮件,但替换其中的某些部分。我想在数字反向引用上使用str_replace,就像这样,但它不起作用

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

知道我做错了什么吗?

您在实际字符串
$0
上使用的是
str\u replace
,而不是它引用的反向引用,这就是它不起作用的原因

您希望在执行
preg\u replace
时执行str\u replace,因此可以使用
preg\u replace\u回调
使用回调函数获取“电子邮件部分”,并在正则表达式替换期间对其执行字符串操作

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

$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\u highlighted=“我的电子邮件是aaaazz@gmail.com";
结果:
我的电子邮件是bbbbzz@gmail.com

请注意,
$pattern
中对regex的更改,将电子邮件分为两部分-在
@
之前,该部分包括
@
和域名。它们在回调函数中作为
$matches[1]
$matches[2]
访问

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

$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];
}
您可以将电子邮件分为三部分(在
@
之前,
@
以及
@
之后的所有内容)。您可以使用以下内容:

$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]);
}

str_replace
在调用时运行,而不是作为绑定运行。
$0
中没有
a
,因此它保持不变。您可能想使用
preg\u replace\u callback
。感谢您的时间和专业知识。这正是我想要的。非常感谢。