Reputation: 1813
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?
Upvotes: 2
Views: 7548
Reputation: 15141
You can try this one:
function isUsed($string_to_search, $source_String) {
if (preg_match("/$string_to_search/", $source_String)) {
return true;
} else {
return false;
}
}
You can change according to your need.
Case insensitive: preg_match("/$string_to_search/i", $source_String)
Boundry condition: preg_match("/\b$string_to_search\b/i", $source_String)
Special characters: if you have any special characters in your string for your safe side replace it with '\special_character'
Upvotes: 0
Reputation: 23892
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.
Upvotes: 5
Reputation: 720
Please try "preg_match" for matches.
$string = 'test';
if ( preg_match("~\btest\b~",$string) )
echo "matched";
else
echo "no match";
Or try like this
if(stripos($text,$word) !== false)
echo "no match";
else
echo "match";
Upvotes: 0
Reputation: 91
Try This.
function isUsed($sourceStr, $searchPat) {
if (preg_match("/\b".preg_quote($sourceStr)."\b/i", $searchPat)) {
return true;
} else {
return false;
}
}
Upvotes: 2