正则表达式:
'#(?P<ref>.+\d) (?P<name>\w+ [A-Z ]*\w+) (?P<city>.+)#'
- 首先捕获以单个数字结尾的名称之前的任何内容。由于缺少参考编号的示例/格式,我不确定这是否正确。如果这不正确,请删除“.+”和“\d”之间的空格。用键“ref”存储在数组中。
- 捕获具有 0 个或多个中间名的名称。使用键“名称”存储在数组中。
- 捕获名称后的任何内容作为城市名称。将键“城市”存储在数组中。
尝试这个:
$vars = array(
'2E4 766 06 7982 647 5 Joesph Sanchez Zuni',
'2E4 766 06 7982 647 5 Joesph J Sanchez Zuni',
'2E4 766 06 7982 647 5 Joesph J G Sanchez Zuni',
'2E4 766 06 7982 647 5 Joesph Sanchez Los Angeles',
'2E4 766 06 7982 647 5 Joesph J Sanchez Los Angeles',
'2E4 766 06 7982 647 5 Joesph J G Sanchez Los Angeles',
'2E4 766 06 7982 647 5 Joesph Sanchez St. Morel',
'2E4 766 06 7982 647 5 Joesph J Sanchez St. Morel',
'2E4 766 06 7982 647 5 Joesph J G Sanchez St. Morel',
);
$matches = array();
foreach ($vars as $var) {
if (preg_match('#(?P<ref>.+ \d) (?P<name>\w+ [A-Z ]*\w+) (?P<city>.+)#', $var, $matches)) {
echo 'Ref: ', $matches['ref'], '. Name: ', $matches['name'], '. City: ', $matches['city'], "\n";
} else {
echo "No match for $var\n";
}
}
结果:
Ref: 2E4 766 06 7982 647 5. Name: Joesph Sanchez. City: Zuni
Ref: 2E4 766 06 7982 647 5. Name: Joesph J Sanchez. City: Zuni
Ref: 2E4 766 06 7982 647 5. Name: Joesph J G Sanchez. City: Zuni
Ref: 2E4 766 06 7982 647 5. Name: Joesph Sanchez. City: Los Angeles
Ref: 2E4 766 06 7982 647 5. Name: Joesph J Sanchez. City: Los Angeles
Ref: 2E4 766 06 7982 647 5. Name: Joesph J G Sanchez. City: Los Angeles
Ref: 2E4 766 06 7982 647 5. Name: Joesph Sanchez. City: St. Morel
Ref: 2E4 766 06 7982 647 5. Name: Joesph J Sanchez. City: St. Morel
Ref: 2E4 766 06 7982 647 5. Name: Joesph J G Sanchez. City: St. Morel