正则表达式替换,电子邮件正文中的电子邮件地址

Regex replace, email address from inside email body

我有(很多)电子邮件正文中包含类似 < asd@somewhere.co > 的地址。

我想从邮件正文中删除 < 和 >,但只在里面有和 @ 的地方(正文中也有 HTML 标签,必须保留)。

我可以用这个正则表达式匹配地址:

^<.[^@]+.@.[^@]+.>$

,但是如何只用地址替换它而不用 < 或 >?

应该这样做...

<?php
$string = '< asd@somewhere.co >';
echo preg_replace('~<\s*(.*?@.*?)\s*>~', '', $string);
?>

搜索 'greater than',可选的前导空格,每个字符直到第一个 @,然后每个字符直到第一个 'less than',带有可选的尾随空格。

要搜索您需要使用的地址:

(?:<)([^>]*@[^>]*)(?:>)

Please see Regex 101 here. 我在尖括号中使用了非捕获组,因此实际上只会捕获它们之间的内容(而且我没有为电子邮件使用特别好的正则表达式,但这应该是很容易调整)。

您应该能够将以上内容与 preg_replace_all() 反向引用一起使用。

I have (many) emails which contain addresses like < asd@somewhere.co > inside the body.

I wish to remove the < and > from the email body, but only where there is and @ inside (there are HTML tags in the body too, which must stay).

简单。这个概念被称为切片。

$email = '<asd@somewhere.co>';


if( strpos( $email, '@' ) ) {

    $new_email = substr( $email, 1, strlen($email)-2 );
    echo $new_email;
}

输出:asd@somewhere.co