Reputation: 247
I have (many) emails which contain addresses like < [email protected] > 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 > ?
Upvotes: 1
Views: 820
Reputation: 10390
I have (many) emails which contain addresses like < [email protected] > 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 = '<[email protected]>';
if( strpos( $email, '@' ) ) {
$new_email = substr( $email, 1, strlen($email)-2 );
echo $new_email;
}
Outputs: [email protected]
Upvotes: 1
Reputation: 12485
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.
Upvotes: 1
Reputation: 23882
This should do it...
<?php
$string = '< [email protected] >';
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.
Upvotes: 4