How does this RegEx for parsing emails work in PHP?
- by George Edison
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
)
)