How to find full words only in string
To see if a particular word is in a string, you can use a regular expression with word boundaries, like so:
$str = "By ILI LIKUALAYANA MOKHTAKUALAR AND G. SURACH Datuk Dr Hasan Ali says he has no intention of joining Umno. Pic by Afendi Mohamed KUALA LUMPUR: FORMER Selangor Pas commissioner Datuk Dr Hasan Ali has not ruled out the possibility of returning to Pas' fold";
$search = "KUALA";
if (preg_match("/\b$search\b/", $str)) {
// word found
}
Here \b
means "boundary of a word". It doesn't actually match any characters, just boundaries, so it matches the edge between words and spaces, and also matches the edges at the ends of the strings.
If you need to make it case-insensitive, you can add i
to the end of the match string like this: "/\b$search\b/i"
.
If you need to know where in the string the result was, you can add a third $matches
parameter which gives details about the match, like this:
if (preg_match("/\b$search\b/", $str, $matches)) {
// word found
$position = $matches[1];
}