Question

I have to extract the email from the following string:

$string = 'other_text_here to=<my.email@domain.fr> other_text_here <my.email@domain.fr> other_text_here';

The server send me logs and there i have this kind of format, how can i get the email into a variable without "to=<" and ">"?

Update: I've updated the question, seems like that email can be found many times in the string and the regular expresion won't work well with it.

Was it helpful?

Solution

You can try with a more restrictive Regex.

$string = 'other_text_here to=<my.email@domain.fr> other_text_here';
preg_match('/to=<([A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4})>/i', $string, $matches);
echo $matches[1];

OTHER TIPS

Simple regular expression should be able to do it:

$string = 'other_text_here to=<my.email@domain.fr> other_text_here';
preg_match( "/\<(.*)\>/", $string, $r );
$email = $r[1];

When you echo $email, you get "my.email@domain.fr"

Try this:

<?php
$str = "The day is <tag> beautiful </tag> isn't it? "; 
preg_match("'<tag>(.*?)</tag>'si", $str, $match);
$output = array_pop($match);
echo $output;
?>

output:

beautiful

Regular expression would be easy if you are certain the < and > aren't used anywhere else in the string:

if (preg_match_all('/<(.*?)>/', $string, $emails)) {
    array_shift($emails);  // Take the first match (the whole string) off the array
}
// $emails is now an array of emails if any exist in the string

The parentheses tell it to capture for the $matches array. The .* picks up any characters and the ? tells it to not be greedy, so the > isn't picked up with it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top