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

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).

I can match the address with this regex:

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

, But how do I replace this with just the address and no < or > ?

To search the address you'll want to use something like this:

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

Please see Regex 101 here. I'm using non-capturing groups for the angle brackets so only what is between them will actually be captured (and I'm not using a particularly good regex for emails, but that should be easy enough to adjust).

You should be able to use the above with preg_replace_all() and the $1 backreference.

This should do it...

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

Search for 'greater than', optional leading whitespace, every character until the first @, then every character until the first 'less than', with optional trailing whitespace.

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).

Simple. The concept is known as slicing.

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


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

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

Outputs: asd@somewhere.co