Search code examples
phpregexpreg-match

PHP - Exact match string in a sentence


I have the following function to do a "exact match" of a pattern($searchPat) in a sentence ($sourceStr)

function isUsed($sourceStr, $searchPat) {
 if (strpos($sourceStr, $searchPat) !== false) {
    return true;
    } else {
    return false;
    }
}

However, this doesn't do an exact match. I changed the function as follows but this doesn't even execute.

function isUsed($sourceStr, $searchPat) {
if (preg_match("~\b[$sourceStr]\b~", $searchPat)) {
    return true;
    } else {
    return false;
    }
}

How could I do an exact match please?


Solution

  • The [] is a character class. That lists characters you want to allow, for example [aeiou] would allow a vowel. Your variables are also in the inverted order, pattern first, then string to match against. Try this:

    function isUsed($sourceStr, $searchPat) {
         if (preg_match("~\b$searchPat\b~", $sourceStr)) {
             return true;
         } else {
             return false;
         }
    }
    

    Additional notes, this is case sensitive, so Be won't match be. If the values you are passing in are going to have special characters the preg_quote function should be used, preg_quote($variable, '~'). You also may want to concatenate the variable so it is clear that that is a variable and not part of the regex. The $ in regex means the end of the string.