开发者

String manipulation/parsing in PHP

I've a开发者_如何学Python string in the following format:

John Bo <jboe@gmail.com>, abracadbra@gmail.com, <asking@gmail.com>...

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

=Rajesh=


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 a@b.com <b@a.com> (unless you really would want both extracted in that case).

$str = 'John Bo <jboe@gmail.com>, abracadbra@gmail.com, <asking@gmail.com>';
 
$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) "jboe@gmail.com"
  [1]=>
  string(20) "abracadbra@gmail.com"
  [2]=>
  string(16) "asking@gmail.com"
}


One-liner no loops!

$str = 'John Bo <jboe@gmail.com>, abracadbra@gmail.com, <asking@gmail.com>';

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

print_r($extracted_emails);

requires PHP 5.3


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

<?php

$emailstring = "John Bo <jboe@gmail.com>,<other@email.com>, abracadbra@gmail.com, <asking@gmail.com>";
$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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜