首页 > 解决方案 > PHP preg_match_all() 匹配除介词以外的所有单词,形容词如数组中其他不太重要的单词

问题描述

PHP preg_match_all() 匹配数组中除某些单词之外的所有单词。

$input = 'Lorem Ipsum is simply dummy text of the printing industry.';
$except = array('and', 'the', 'text', 'simply');
preg_match_all('/(?<match>\w{3,}+)/', $input, $matches, PREG_PATTERN_ORDER);
print_r($matches['match']);

这给了所有不需要的词。

Array
(
    [0] => Lorem
    [1] => Ipsum
    [2] => simply
    [3] => dummy
    [4] => text
    [5] => the
    [6] => printing
    [7] => industry
)

只需要返回重要的单词而不是形容词或介词形容词,就像数组中其他不太重要的单词一样。

$except = array('and', 'the', 'text', 'simply');

如果我们可以为此目的使用一个函数会更好。

标签: phpregexartificial-intelligence

解决方案


构建一个带有锚定在单词边界的负前瞻的正则表达式:

'~\b(?!(?:and|the|text|simply)\b)\w{3,}~'

查看正则表达式演示

细节

  • \b- 单词边界
  • (?!(?:and|the|text|simply)\b)- no and, the, 等,因为整个单词被允许紧跟在当前位置的右侧
  • \w{3,}- 3 个或更多字字符。

PHP 演示

$input = 'Lorem Ipsum is simply dummy text of the printing industry.';
$except = array('and', 'the', 'text', 'simply');
if (preg_match_all('/\b(?!(?:' . implode('|', $except) . ')\b)\w{3,}/', $input, $matches)) {
  print_r($matches[0]);
}

输出:

Array
(
    [0] => Lorem
    [1] => Ipsum
    [2] => dummy
    [3] => printing
    [4] => industry
)

推荐阅读