Crisan Raluca Teodora
Crisan Raluca Teodora

Reputation: 1293

PHP extract one part of a string

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.

Upvotes: 1

Views: 133

Answers (4)

Matt S
Matt S

Reputation: 15364

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.

Upvotes: 0

Evandro Henrique
Evandro Henrique

Reputation: 36

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];

Upvotes: 2

Tito
Tito

Reputation: 59

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

Upvotes: 0

pp19dd
pp19dd

Reputation: 3633

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]"

Upvotes: 1

Related Questions