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

前端 未结 7 2159
时光说笑
时光说笑 2020-11-30 03:19

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(\         


        
相关标签:
7条回答
  • 2020-11-30 04:08

    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 a+b@google.com.sg, 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 => 'test1+2@gmail.com',
      1 => 'test-2@yahoo.co.jp',
      2 => 'test@test.com',
      3 => 'test@test.co.uk',
      4 => 'test@google.com.sg',
    )
    
    0 讨论(0)
提交回复
热议问题