Your code is almost perfect, you just need to replace preg_match(...)
with preg_match_all(...)
views:
45answers:
3
+1
A:
steven_desu
2010-10-10 16:19:37
Thank you so much!! I am getting close now. My output however looks a little strange to me. I seem to be getting arrays within my array as follows: Array ( [0] => Array ( [0] => [email protected] ) [1] => Array ( [0] => edu ) )
HumbleHelper
2010-10-10 17:00:53
I am looking for simply one array with each key containing an e-mail address.
HumbleHelper
2010-10-10 17:01:57
@HumbleHelper preg_replace_all will create new array elements for submatches of anything that was in parentheses in the original pattern. You had parentheses around the last part is the domain in your pattern. To fix this you can just append $matches = $matches[0] at the end. Also, look at Clay Hinson's answer. He deserves the accepted answer.
steven_desu
2010-10-11 02:04:33
+1
A:
I know this is not the question you asked but I noticed that your regex is not accepting any address like "[email protected]" or any address with a subdomain. You could replace it with something like :
/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}/
which will regect less valid e-mail (although it is not perfect).
I also suggest you read this article on e-mail validation, it is pretty good and informative.
@Steven_desu : I would "up" your answer, but being new here, I don't have the rep yet. :(
Eric-Karl
2010-10-10 17:13:22
+1
A:
You're pretty close, but the regex wouldn't catch all email formats, and you don't need to specify A-Za-z, you can just use the "i" flag to mark the entire expression as case insensitive. There are email format cases that are missed (especially subdomains), but this catches the ones I tested.
$string = file_get_contents("example.txt"); // Load text file contents
// don't need to preassign $matches, it's created dynamically
// this regex handles more email address formats like [email protected], and the i makes it case insensitive
$pattern = '/[a-z0-9_\-\+]+@[a-z0-9\-]+\.([a-z]{2,3})(?:\.[a-z]{2})?/i';
// preg_match_all returns an associative array
preg_match_all($pattern, $string, $matches);
// the data you want is in $matches[0], dump it with var_export() to see it
var_export($matches[0]);
output:
array (
0 => '[email protected]',
1 => '[email protected]',
2 => '[email protected]',
3 => '[email protected]',
4 => '[email protected]',
)
Clay Hinson
2010-10-10 17:19:37
+1 for more detail than my answer, example code, and a pattern that catches subdomains. This should be accepted answer.
steven_desu
2010-10-11 01:59:12