完全匹配的Strpos

时间:2011-10-11 23:00:07

标签: php html regex

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

这就是我现在所拥有的:

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

这很好用,并且实际上找到了搜索字符串中的关键字,但问题是 strpos 与完全短语或单词不匹配。

例如,如果'PHP'一词在字符串中,则搜索'HP'将返回true。

我知道 preg_split 和正则表达式可用于进行完全匹配,但就我而言,我不知道每次搜索的关键字是什么,因为关键字是用户输入

所以关键字可以是“热棒”,“AC / DC”,“标题:主题”等等...... 这意味着我不能分开单词并单独检查它们,因为我必须使用某种动态模式来表示正则表达式。

如果有人知道一个好的解决方案,我会非常感激。

我的意思是,基本上我只需要完全匹配,所以如果KW是“Prof”,那么如果搜索到的字符串中的匹配是“Prof”并且没有任何其他字符围绕它,则返回true。 /> 例如,“专业”必须是假的。

2 个答案:

答案 0 :(得分:4)

您可以使用字词边界\b

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

例如:

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

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

答案 1 :(得分:1)

就我而言,当句子中存在professional时,我需要完全匹配professional.bowler

preg_match('/\bprofessional\b/i', 'Im a professional.bowler');返回int(1)的位置。

要解决此问题,我使用数组在键上使用isset查找完全匹配的单词。

Detection Demo

$wordList = array_flip(explode(' ', 'Im a professional.bowler'));
var_dump(isset($wordList['professional'])); //false
var_dump(isset($wordList['professional.bowler'])); //true

该方法也适用于目录路径,例如在更改php include_path时,而不是使用preg_replace这是我的特定用例。

Replacement Demo

$removePath = '/path/to/exist-not' ;
$includepath = '.' . PATH_SEPARATOR . '/path/to/exist-not' . PATH_SEPARATOR . '/path/to/exist';
$wordsPath = str_replace(PATH_SEPARATOR, ' ', $includepath);
$result = preg_replace('/\b' . preg_quote($removePath, '/'). '\b/i', '', $wordsPath);
var_dump(str_replace(' ', PATH_SEPARATOR, $result));
//".:/path/to/exist-not:/path/to/exist"

$paths = array_flip(explode(PATH_SEPARATOR, $includepath));
if(isset($paths[$removePath])){
    unset($paths[$removePath]);
}
$includepath = implode(PATH_SEPARATOR, array_flip($paths));
var_dump($includepath);
//".:/path/to/exist"
相关问题