Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
578 views
in Technique[技术] by (71.8m points)

regex - 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. How do I do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]',
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...