搜索带有部分和完整单词的正则表达式单词边界

时间:2018-08-09 07:12:16

标签: php regex preg-match

$str = 'Company Name Internal Transport Worldwide  
Account Manager New Business';

I tried:
$re = "/\b(internal.transport|accountmanag|account.manag).*\W/mi";  
// result: Internal Transport 

$re = "/\b(internal.transport|accountmanag|account.manag)\w+/mi";  
// result: Account Manager

$re = "/\b(internal.transport|accountmanag.`*|account.manag.`*)\W/mi";  
// result: Internal Transport, Account Manager New

preg_match($re, $str, $matches);

我正在寻找结果:
-内部运输
-客户经理

执行此操作的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

您可以使用

'~\b(?:internal\Wtransport|accountmanag|account\Wmanag)\w*~i'

请参见regex demo

详细信息

  • \b-单词边界
  • (?:internal\Wtransport|accountmanag|account\Wmanag)-与三个备选方案中的任何一个匹配的非捕获交替组:
    • internal\Wtransport-internal,一个非单词字符transport
    • |-或
    • accountmanag-accountmanag
    • |-或
    • account\Wmanag-account,一个非单词字符manag
  • \w*-0个以上的字符字符。

请参见PHP demo

$str = 'Company Name Internal Transport Worldwide  
Account Manager New Business';

$re = "/\b(?:internal\Wtransport|accountmanag|account\Wmanag)\w*/i";  
if (preg_match_all($re, $str, $matches)) {
    print_r($matches[0]);
}

输出:

Array
(
    [0] => Internal Transport
    [1] => Account Manager
)