HumbleHelper HumbleHelper - 11 months ago 31
PHP Question

In PHP, how do I extract multiple e-mail addresses from a block of text and put them into an array?

I have a block of text from which I want to extract the valid e-mail addresses and put them into an array. So far I have...

$string = file_get_contents("example.txt"); // Load text file contents
$matches = array(); //create array
$pattern = '/[A-Za-z0-9_-]+@[A-Za-z0-9_-]+\.([A-Za-z0-9_-][A-Za-z0-9_]+)/'; //regex for pattern of e-mail address
preg_match($pattern, $string, $matches); //find matching pattern

However, I am getting an array with only one address. Therefore, I am guessing I need to cycle through this process somehow, but am uncertain how to? Could someone help me?

Thanks in advance!


Your code is almost perfect, you just need to replace preg_match(...) with preg_match_all(...)