How does this RegEx for parsing emails work in PHP?
Posted
by George Edison
on Stack Overflow
See other posts from Stack Overflow
or by George Edison
Published on 2010-04-19T21:15:17Z
Indexed on
2010/04/19
21:23 UTC
Read the original article
Hit count: 258
Okay, I have the following PHP code to extract an email address of the following two forms:
Random Stranger <[email protected]>
[email protected]
Here is the PHP code:
// The first example
$sender = "Random Stranger <[email protected]>";
$pattern = '/([\w_-]*@[\w-\.]*)|.*<([\w_-]*@[\w-\.]*)>/';
preg_match($pattern,$sender,$matches,PREG_OFFSET_CAPTURE);
echo "<pre>";
print_r($matches);
echo "</pre><hr>";
// The second example
$sender = "[email protected]";
preg_match($pattern,$sender,$matches,PREG_OFFSET_CAPTURE);
echo "<pre>";
print_r($matches);
echo "</pre>";
My question is... what is in $matches
? It seems to be a strange collection of arrays. Which index holds the match from the parenthesis? How can I be sure I'm getting the email address and only the email address?
Update:
Here is the output:
Array
(
[0] => Array
(
[0] => Random Stranger
[1] => 0
)
[1] => Array
(
[0] =>
[1] => -1
)
[2] => Array
(
[0] => [email protected]
[1] => 5
)
)
Array
(
[0] => Array
(
[0] => [email protected]
[1] => 0
)
[1] => Array
(
[0] => [email protected]
[1] => 0
)
)
© Stack Overflow or respective owner