与精确匹配的Strpos [英] Strpos with exact matches

查看:112
本文介绍了与精确匹配的Strpos的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在php中有一个函数,我想在一个字符串上执行一个简单的搜索,使用kw作为搜索短语,如果找到则返回true。





  for($ i = 0; $ i< count($ search_strings); $ i ++ ){
$ pos = strpos($ search_strings [$ i],$ kw_to_search_for);
}

这个工作正常,并且确实在字符串beeing中查找关键字,但问题在于 strpos 与确切的短语或单词不匹配。 例如,搜索'HP'<如果单词'PHP'位于字符串中, / strong>将返回true。

我知道 preg_split 和正则表达式,可用于执行完全匹配,但在我的情况下,我不知道每个搜索的关键字是什么,因为关键字是用户输入的

因此关键字可以是热棒,AC / DC,标题:主题等等等等。
这意味着我如果有人知道一个好的解决方案,我将非常感激,因为我不得不分开单词,并单独检查他们,因为我将不得不使用某种动态模式的正则表达式。



它。



我的意思是,基本上我只需要精确匹配,所以如果KW是Prof,那么如果搜索字符串中的匹配是Prof并且没有任何其他字符,则这将返回true。

例如Professional必须是FALSE。

解决方案

您可以使用单词边界 \ b

  if(preg_match(/ \b.preg_quote($ kw_to_search_for)。\b / i,$ search_strings [$ i])){
//找到
}

  echo preg_match(/ \bProfessional\b / i,'Prof'); // 0 
echo preg_match(/ \ bProf\b / i,'Prof'); // 1

/ i 修饰符不区分大小写。


I have a function in php which I would like to perform a simple search on a string, using a kw as the search phrase, and return true if found.

This is what I have now:

for($i=0; $i<count($search_strings); $i++){
   $pos = strpos($search_strings[$i], $kw_to_search_for);
}

This works fine, and does actually find the Keyword inside the string beeing searched, but the problem is that strpos doesn't match exact phrases or words.

For instance, a search for 'HP' would return true if the word 'PHP' was in the string.

I know of preg_split and regular expressions which can be used to do exact matches, but in my case I don't know what the keyword is for every search, because the keyword is user-inputted.

So the keyword could be "hot-rods", "AC/DC", "Title:Subject" etc etc... This means I cannot split the words and check them separately because I would have to use some kind of a dynamic pattern for the regex.

If anybody know of a good solution I would much appreciate it.

I mean, basically I want exact matches only, so if the KW is "Prof" then this will return true if the match in the searched string is "Prof" and doesn't have any other characters surrounding it.
For instance "Professional" would have to be FALSE.

解决方案

You can use word boundaries \b:

if (preg_match("/\b".preg_quote($kw_to_search_for)."\b/i", $search_strings[$i])) {
    // found
}

For instance:

echo preg_match("/\bProfessional\b/i", 'Prof'); // 0
echo preg_match("/\bProf\b/i", 'Prof');         // 1

/i modifier makes it case insensitive.

这篇关于与精确匹配的Strpos的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆