PHP Ferrari
PHP Ferrari

Reputation: 15616

Fetch email id from a string

I have array containing strings in format like:

[email protected] Entry ID: 12321
[email protected] Entry ID: 12322 Entry ID: 12323
[email protected] Entry ID: 12324 Entry ID: 12325 Entry ID: 12326
[email protected] Entry ID: 12327 Entry ID: 12328
[email protected] Entry ID: 12329 Entry ID: 123210

and I want to fetch only email address from each string & push into an array.

I tried http://www.webdeveloper.com/forum/showthread.php?200875-extract-email-from-string-text-%28patterns%29

and many others from Stackoverflow but browser shows blank screen on echo/print_r

Upvotes: -1

Views: 89

Answers (4)

Lix
Lix

Reputation: 47956

I'm making an assumption here that for each line, the seperator between the email and the other data is consistent - a single space.

Simply use the explode() function to split each element by a single space and take the first element of the resulting split. That will be the email.

foreach($arr as $key => $value){
  $parts = explode(" ",$value);
  $email = $parts[0];
}

Here is a live demo

Upvotes: 1

juco
juco

Reputation: 6342

You can explode() the string by a space and array_shit() the first element. Something like:

$emailAddresses = array();
foreach($strings as $string) {
   $emailAddresses[] = array_shift(explode(' ', $string));
}

Avoid using a RegEx unless it's absolutely necessary.

Upvotes: 2

Eernie
Eernie

Reputation: 469

if the string always starts with a email adress. You can work like this:

foreach($emailArray as $value){ 
  $email = explode(" ",$value)[0];
}

Upvotes: 1

Dipesh Parmar
Dipesh Parmar

Reputation: 27364

You need to use regex.

preg_match_all("/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i", $string, $matches);
print_r($matches[0]);

OutPut

Array
(
    [0] => [email protected]
    [1] => [email protected]
    [2] => [email protected]
    [3] => [email protected]
    [4] => [email protected]
)

Upvotes: 0

Related Questions