假设我有一串作者:
$str1="Evans, C. J. and Ebin, Kupper and Nirenberg, Jhon France";
$str2="Evans, C. J.";
如何通过preg_match()
获取 first 姓氏?
输出应分别为:
EvansEbinNirenberg
Evans
谢谢!
答案 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
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]);