开发者

One for the regex gurus

This should be an easy one, but I'm tired and not thinking straight at the time.

I have the following string:

"Brian Hannah <brian@abktech开发者_开发技巧nologies.com>"

I want to extract the name and email address into separate variables using PHP.


Explode('<',$mystring).

If all strings are the same. Trim and remove >


Just for completeness, here's an approach using regular expressions:

preg_match('/^(.*)<(.*)>$/', $s, $matches);

See it working online: ideone

Since the * is greedy in the first match, a string like A<B <c.d> will be parsed as "A<B", "<c.d>", and not "A", "<B <c.d>". To change this write (.*?) instead.


If you have the PHP module mailparse installed, you can use the rfc822-parse-addresses function. There are also regex examples on that page, but they can't handle all the possible permutations. A full regex to decode email address runs to a couple of pages of densely packed regex.


You don't really need the power (and CPU expense) of regular expressions for such simple string manipulation

$str = "Brian Hannah <brian@abktechnologies.com>";

$lt = strpos($str, '<');
$name = substr($str, 0, $lt - 1);
$email = substr($str, $lt + 1, strlen($str) - $lt - 2);


Typically regular expressions are faster than PHP and its string functions. But a more basic approach would be:

strtok($string, "<")  and  $email = strtok(">");


$v= "Brian Hannah <brian@abktechnologies.com>";

$arr = '#[<|>]#';

$d = preg_split($arr, $v);

var_dump( $d ) ;

Values will need to be trim()med tho

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜