我想从包含name (some title), address (may contain commas)
示例:
John Doe PhD., 25 Oak Rd, Ridgeville, WA, USA
Peter Smith PhD. and Hannah Smith, 55 Riverside Ave, Alice Springs, NT, Australia
John Miles, BA, PhD., 152 Rain Rd, Copper Mines, Canada
Cool Company, Inc., 152 Great Rd, NZ
假设这些行中的每一行都存储在变量$string
中。
预期产出:
John Doe PhD.
Peter Smith PhD. and Hannah Smith
John Miles, BA, PhD.
Cool Company, Inc.
我做了什么 - 我准备了一系列标题
$titles = array("PhD.", "MA", "MSc", "BA", "Inc.");
并希望在$string
中搜索任何$titles
。
问题是我需要找到字符串中的最后一个标题(所以某种向后搜索),然后提取包含该标题的子字符串(加上字符串开头的所有内容) - 同时这样做,而不是结束直到下一个逗号(见第2行 - 夫妻)所以我有全名(夫妻的名字)。
答案 0 :(得分:0)
$str = "Peter Smith PhD. and Hannah Smith, 55 Riverside Ave, Alice Springs, NT, Australia";
$substring = getSubstring($str);
echo $substring;
function getSubString($str) {
$titles = array("PhD.", "MA", "MSc", "BA", "Inc.");
foreach ($titles as $key => $val) {
//Search for title in string
if(strpos($str, $val)) {
//if found then find the first occurance of the title in string in reverse
$lastTitlePosition = strrpos($str, $val, 0);
//then find the next comma after title
$commaPositionAfterTitle = strpos($str, ',', $lastTitlePosition);
//then return substring till that comma of substring where title found
return substr($str,0,$commaPositionAfterTitle );
} else {
return "not found";
}
}
}