1

I have to extract the email from the following string:

$string = 'other_text_here to=<[email protected]> other_text_here <[email protected]> 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.

4 Answers 4

2

You can try with a more restrictive Regex.

$string = 'other_text_here to=<[email protected]> other_text_here';
preg_match('/to=<([A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4})>/i', $string, $matches);
echo $matches[1];
Sign up to request clarification or add additional context in comments.

Comments

1

Simple regular expression should be able to do it:

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

When you echo $email, you get "[email protected]"

1 Comment

Other solutions here use (.*?), which is very properly done for most regex, handling loose leading or trailing < and > after the email address. However, in my opinion, you can't anticipate such characters here unless you were extracting a bunch of emails from a block of text, so you'd need another method anyhow. In other words, there is a reasonable expectation of a format limit.
0

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

Comments

0

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.

2 Comments

It wont let me accept the answere yet, i will do it asap, thx
I've updated the question, i've found out that the server can print into the logs on the that email many times, and the regular expresion is not working well in that case.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.