Anonymous12345 Anonymous12345 - 11 months ago 157
PHP Question

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<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.