php - 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');
如果我们可以为此目的使用一个函数会更好。
解决方案
构建一个带有锚定在单词边界的负前瞻的正则表达式:
'~\b(?!(?:and|the|text|simply)\b)\w{3,}~'
查看正则表达式演示
细节
\b
- 单词边界(?!(?:and|the|text|simply)\b)
- noand
,the
, 等,因为整个单词被允许紧跟在当前位置的右侧\w{3,}
- 3 个或更多字字符。
$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
)
推荐阅读
- php - 无法通过 WSDLDocument.php (PHP SOAP) 生成 XML
- javascript - 如何在 JavaScript 中缩短 OR 条件?
- javascript - 搜索谷歌的输入
- ios - 调整按钮中的图像大小
- sql - 在 SQL 查询中根据最小日期和最大日期组合行
- java - 二和三——数据结构设计
- javascript - 当设备宽度小于 1200px 时,scrollIntoView 不起作用
- java - 带有 sectionindexer 的 Recyclerview (gridview)
- java - 如果写入的值始终相同,那么延迟初始化引用是否是线程安全的?
- javascript - React-table 全选选择框