正则表达式分拆双公司名称?

时间:2011-06-17 13:16:46

标签: php regex

我有一个公司名称列表,有时包含两个公司名称,由/分隔。

我想将它们分开,如果只有两个,那就选择第二家公司。

我遇到的一个问题是,公司名称通常也包含A/S之类的内容。

更新数据:

Food Done Inc.
Marina-Dock Salt Fishing Ltd
Frederikson Bay K/S
Food Bridge S/A/Natural Samslo
Anabelle Nautico A/S/Frederikson Bay K/S
Anabelle Nautico A/S/Food Done Inc.
Sono Sara And Co/33/36 Partnership
C-4 Summa A/C Development Sys/Finfruit Inc
A/S NOVO Fishing
A/S NOVO Fishing/Kurlag Tours
D & D 23/21 LLC/A-OK Boats
...

现在,如果第一个简单的字符串测试验证/是名称的一部分,我只检查部件。

然后我运行一个正则表达式并捕获/的偏移量,我认为这是最好的分割位置,但对于那些/的单个条目,它会失败。

我认为通过命名匹配可以更轻松地解决这个问题,而不是在特定位置拆分,这样我就可以在运行后选择名称匹配。

这是一种存根我可以做到,但我有问题找到正确的正则表达式:

$pattern = '((?P<named>##company-1##)|(##company-1##/(?P<named>##company-2##))';
$result = preg_match($pattern, $name, $matches);
if (!$result) {
   // pattern not useful.
} else {
   $company = $match['named'];
   echo $company, "\n";
}

我认为公司的模式可以/总是相同但我总是偶然发现多个/的问题。

任何帮助表示感谢。

2 个答案:

答案 0 :(得分:1)

示例代码:

<?php

$companies = array(
        'Food Done Inc.',
        'Marina-Dock Salt Fishing Ltd',
        'Frederikson Bay K/S',
        'Food Bridge S/A/Natural Samslo',
        'Anabelle Nautico A/S/Frederikson Bay K/S',
        'Anabelle Nautico A/S/Food Done Inc.'
    );
$pattern = '~^([^/]+(?:/[a-z])?)/(.{2,})$~i';
foreach ($companies as $company) {
    if (preg_match($pattern, $company, $matches)) {
        echo $matches[1] . ' - ' . $matches[2] . "\n";
    } else {
        echo $company . "\n";
    }
}

与提供的公司合作。

答案 1 :(得分:1)

这是你想要的吗?

$arr = array(
    'Food Done Inc.',
    'Marina-Dock Salt Fishing Ltd',
    'Frederikson Bay K/S',
    'Food Bridge S/A/Natural Samslo',
    'Anabelle Nautico A/S/Frederikson Bay K/S',
    'Anabelle Nautico A/S/Food Done Inc.',
    'Sono Sara And Co/33/36 Partnership',
    'C-4 Summa A/C Development Sys/Finfruit Inc',
    'A/S NOVO Fishing/Kurlag Tours',
    'A/S NOVO Fishing',
    'D & D 23/21 LLC/A-OK Boats'
);


foreach ($arr as $name) {
    preg_match('~(?P<name>(?:./. )?[^/]+(?: ./.)?)$~', $name, $match);
    echo $name ,"\t=> ", $match['name'], "\n";
}

<强>输出:

Food Done Inc.  => Food Done Inc.
Marina-Dock Salt Fishing Ltd    => Marina-Dock Salt Fishing Ltd
Frederikson Bay K/S     => Frederikson Bay K/S
Food Bridge S/A/Natural Samslo  => Natural Samslo
Anabelle Nautico A/S/Frederikson Bay K/S        => Frederikson Bay K/S
Anabelle Nautico A/S/Food Done Inc.     => Food Done Inc.
Sono Sara And Co/33/36 Partnership      => 36 Partnership
C-4 Summa A/C Development Sys/Finfruit Inc      => Finfruit Inc
A/S NOVO Fishing/Kurlag Tours   => Kurlag Tours
A/S NOVO Fishing        => A/S NOVO Fishing
D & D 23/21 LLC/A-OK Boats      => A-OK Boats