Reputation: 15616
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.
and many others from Stackoverflow but browser shows blank screen on echo/print_r
Upvotes: -1
Views: 89
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];
}
Upvotes: 1
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
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
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