如何检查句子中是否存在某个单词
例如,如果我的句子是 $sent = 'how are you';
并且如果我使用 strstr($sent, $key)
它将返回 true
因为我的句子中有 ho
。
我正在寻找的是一种返回 true 的方法,如果我只搜索 how、are 或 you。我该怎么做?
For example, if my sentence is $sent = 'how are you';
and if I search for $key = 'ho'
using strstr($sent, $key)
it will return true
because my sentence has ho
in it.
What I'm looking for is a way to return true if I only search for how, are or you. How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用函数
preg-match
,该函数使用 带有单词边界的正则表达式:You can use the function
preg-match
that uses a regex with word boundaries:如果您想检查同一字符串中的多个单词,并且正在处理大字符串,那么这会更快:
然后您可以使用以下命令检查单词:
此方法速度快如闪电。
但要检查短字符串中的几个单词,请使用 preg_match。
更新:
如果您确实要使用它,我建议您像这样实现它以避免出现问题:
然后双空格、换行符、标点符号和大写字母不会产生漏报。
此方法在检查大字符串(即整个文本文档)中的多个单词时要快得多,但如果您只想查找正常大小的字符串中是否存在单个单词,则使用 preg_match 会更有效。
If you want to check for multiple words in the same string, and you're dealing with large strings, then this is faster:
Then you can check for words with:
This method is lightning fast.
But for checking for a couple of words in short strings then use preg_match.
UPDATE:
If you're actually going to use this I suggest you implement it like this to avoid problems:
Then double spaces, linebreaks, punctuation and capitals won't produce false negatives.
This method is much faster in checking for multiple words in large strings (i.e. entire documents of text), but it is more efficient to use preg_match if all you want to do is find if a single word exists in a normal size string.
您可以做的一件事是将句子按空格分解成数组。
首先,您需要删除任何不需要的标点符号。
以下代码删除除字母、数字或空格之外的任何内容:
现在,您所拥有的只是由空格分隔的单词。创建一个按空格分割的数组...
最后,您可以进行检查。以下是所有步骤的组合。
One thing you can do is breaking up your sentence by spaces into an array.
Firstly, you would need to remove any unwanted punctuation marks.
The following code removes anything that isn't a letter, number, or space:
Now, all you have are the words, separated by spaces. To create an array that splits by space...
Finally, you can do your check. Here are all the steps combined.
@codaddict的答案在技术上是正确的,但如果您正在搜索的单词是由用户提供的,则您需要转义搜索单词中具有特殊正则表达式含义的任何字符。例如:
@codaddict's answer is technically correct but if the word you are searching for is provided by the user, you need to escape any characters with special regular expression meaning in the search word. For example:
认识到 Abhi 的答案后,提出了一些建议:
我根据记录的 preg_match 返回值在比较中添加了显式 === 1
With recognition to Abhi's answer, a couple of suggestions:
I added explicit === 1 to the comparison based on the documented preg_match return values