Question : Extract only email addresses

Hello.

I have 1 txt called (mails.txt). In this files there are stored email addresses and usernames. E-mail and usernames are separated by " | " symbol.  for examples:

[email protected] | user1
[email protected] | user2
[email protected] | user3

I want to know how to extract only email addresses from the mails.txt file?

Thank you

Answer : Extract only email addresses

Hi there,

Try this function:

function extractEmails($string) {
      $emails = array();
      preg_match_all("/\b\w+\@\w+[\.\w+]+\b/", $string, $out);
      foreach($out[0] as $email) {
            $emails[] = strtolower($email);
      }
      if (!empty($emails)) {
            return $emails;
      }
      return false;
}

Now to call it - you can use a string:

$content = "some string with [email protected], and another email [email protected]";

or use output buffering to get the content from the file:

ob_start();
require_once('file_with_content.php');
$content = ob_get_clean();

then simply call the funciton and pass the $content to it as a parameter:

$emails = extractEmails($content);

Now $emails array stores all email addresses found in the string / or file.

you can print the array to display all these or do whatever you need with it:

echo "<pre>";
print_r($emails);
echo "</pre>";
Random Solutions  
 
programming4us programming4us