Rajesh Beri
Rajesh Beri

Reputation: 33

String manipulation/parsing in PHP

I've a string in the following format:

John Bo <[email protected]>, [email protected], <[email protected]>...

How can I parse the above string in PHP and just get the email addresses? Is there an easy way to parse?

=Rajesh=

Upvotes: 0

Views: 150

Answers (4)

alex
alex

Reputation: 490657

You could of course just use a regex on the string, but the RFC complaint regex is a monster of a thing.

It would also fail in the unlikely (but possible event) of [email protected] <[email protected]> (unless you really would want both extracted in that case).

$str = 'John Bo <[email protected]>, [email protected], <[email protected]>';
 
$items = explode(',', $str);
$items = array_map('trim', $items);
 
$emails = array();
 
foreach($items as $item) {
    preg_match_all('/<(.*?)>/', $item, $matches);
    
    if (empty($matches[1])) {
       $emails[] = $item;
       continue;
    }
    $emails[] = $matches[1][0];
}
 
var_dump($emails);

Ideone.

Output

array(3) {
  [0]=>
  string(14) "[email protected]"
  [1]=>
  string(20) "[email protected]"
  [2]=>
  string(16) "[email protected]"
}

Upvotes: 1

Galen
Galen

Reputation: 30180

One-liner no loops!

$str = 'John Bo <[email protected]>, [email protected], <[email protected]>';

$extracted_emails = array_map( function($v){ return trim( end( explode( '<', $v ) ), '> ' ); }, explode( ',', $str ) );

print_r($extracted_emails);

requires PHP 5.3

Upvotes: 0

Eric
Eric

Reputation: 25

Use int preg_match_all (string pattern, string subject, array matches, int flags) which will search "subject" for all matches of the regex (perl format) pattern, fill the array "matches" will all matches of the rejex and return the number of matches.

See http://www.regular-expressions.info/php.html

Upvotes: 0

Jared Farrish
Jared Farrish

Reputation: 49238

The most straight-forward way would be to (also I am terrible at regex):

<?php

$emailstring = "John Bo <[email protected]>,<[email protected]>, [email protected], <[email protected]>";
$emails = explode(',',$emailstring);

for ($i = 0; $i < count($emails); $i++) {
    if (strpos($emails[$i], '<') !== false) {
        $emails[$i] = substr($emails[$i], strpos($emails[$i], '<')+1);
        $emails[$i] = str_replace('>','',$emails[$i]);
    }
    $emails[$i] = trim($emails[$i]);
}

print_r($emails);

?>

http://codepad.org/6lKkGBRM

Upvotes: 0

Related Questions