开发者

Strpos with exact matches

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<c开发者_开发问答ount($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.


In my case I needed to match exactly professional when professional.bowler existed in the sentence.

Where preg_match('/\bprofessional\b/i', 'Im a professional.bowler'); returned int(1).

To resolve this I resorted to arrays to find an exact word match using isset on the keys.

Detection Demo

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

The method also works for directory paths, such as when altering the php include_path, as opposed to using preg_replace which was my specific use-case.

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"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜