1

I wish to split a string.

  • It comprises of ref no., name, and city

example: 2E4 766 06 7982 647 5 Joesph J Sanchez Zuni

  • 2E4 766 06 7982 647 5 is ref no.
  • Joesph J Sanchez is name
  • Zuni is city

Separating Name and City is difficult but I am trying to separate Ref No and Name(NAme City). I formed a regular expression and tested it on: http://www.switchplane.com/awesome/preg-match-regular-expression-tester/?pattern=%22%5Ba-zA-Z%5D%5Ba-z%5Cs.%5D%22&subject=2E4+766+06+7982+647+5+Joesph+J+Sanchez+Zuni

I formed it by thinking Name will always start in Capital Letters and will be followed by a small alphabet or space or dot

But when I use

$keywords = preg_split("[a-zA-Z][a-z\s.]", $strBreak['cust_ref']);

it doesn't work.

Please guide.

4

1 回答 1

1

正则表达式:

'#(?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
于 2013-10-02T14:51:31.997 回答