在php中获取由`和`加入的作者的姓氏

时间:2015-01-26 06:05:15

标签: php preg-match

假设我有一串作者:

$str1="Evans, C. J. and Ebin, Kupper and Nirenberg, Jhon France";
$str2="Evans, C. J.";

如何通过preg_match()获取 first 姓氏?

输出应分别为:

EvansEbinNirenberg
Evans

谢谢!

2 个答案:

答案 0 :(得分:1)

尝试使用explode()

$str1="Evans, C. J. and Ebin, Kupper and Nirenberg, Jhon France";
$last_names = '';
$s = explode(',', $str1);
foreach($s as $v) {
  $n[] = explode(' ',$v);
}
foreach($n as $ln) {
  $last_names .= end($ln);
}
echo $last_names; //EvansEbinNirenbergFrance 

preg_match()

$str = 'Evans, C. J. and Ebin, Kupper and Nirenberg, Jhon France';
preg_match_all('/([A-Z])\w+(?=,)/', $str, $matches);
echo implode('',$matches[0]); //EvansEbinNirenberg 

答案 1 :(得分:1)

您可以使用:

/([A-Z])\w+(?=,)/g

演示:http://regexr.com/3a9kf

PHP代码:

$str1="Evans, C. J. and Ebin, Kupper and Nirenberg, Jhon France";
$str2="Evans, C. J.";

preg_match_all('/([A-Z])\w+(?=,)/',$str1,$matches);
echo implode('',$matches[0])."\n";

preg_match_all('/([A-Z])\w+(?=,)/',$str2,$matches);
echo implode('',$matches[0]);