从字符串中的一组单词中查找单词的最佳方法是什么?
What's the best approach to find words from a set of words in a string?
我必须检测用户提交的字符串中是否存在某些词(甚至是多词,如 "bag of words")。
我需要找到确切的单词,而不是它的一部分,所以 strstr/strpos/stripos
系列不适合我。
我目前的做法(PHP/PCRE regex
)如下:
\b(first word|second word|many other words)\b
还有其他更好的方法吗?我错过了什么重要的东西吗?
字数1500左右
感谢任何帮助
您所演示的正则表达式将起作用。如果单词列表变长或发生变化,维护起来可能会很困难。
如果您需要查找包含 space 的短语并且列表不会增长太多,您使用的方法将适用。
如果您要查找的单词中没有 space,您可以将输入字符串拆分为 space 个字符(\s+
,请参阅 https://www.php.net/manual/en/function.preg-split.php ), then check to see if any of those words are in a Set (https://www.php.net/manual/en/class.ds-set.php ) 由您要查找的单词组成。这将是更多的代码,但较少的正则表达式维护,所以 ymmv 基于您的应用程序。
如果集合有 space,请考虑改用 Trie。 Wiktor Stribiżew 建议:https://github.com/sters/php-regexp-trie
我必须检测用户提交的字符串中是否存在某些词(甚至是多词,如 "bag of words")。
我需要找到确切的单词,而不是它的一部分,所以 strstr/strpos/stripos
系列不适合我。
我目前的做法(PHP/PCRE regex
)如下:
\b(first word|second word|many other words)\b
还有其他更好的方法吗?我错过了什么重要的东西吗?
字数1500左右
感谢任何帮助
您所演示的正则表达式将起作用。如果单词列表变长或发生变化,维护起来可能会很困难。
如果您需要查找包含 space 的短语并且列表不会增长太多,您使用的方法将适用。
如果您要查找的单词中没有 space,您可以将输入字符串拆分为 space 个字符(\s+
,请参阅 https://www.php.net/manual/en/function.preg-split.php ), then check to see if any of those words are in a Set (https://www.php.net/manual/en/class.ds-set.php ) 由您要查找的单词组成。这将是更多的代码,但较少的正则表达式维护,所以 ymmv 基于您的应用程序。
如果集合有 space,请考虑改用 Trie。 Wiktor Stribiżew 建议:https://github.com/sters/php-regexp-trie