How to find full words only in string
Just split up the string:
$words = explode(' ',$str);
if (in_array($search,$words)){
echo "FOUND!";
}
Or, if you need the location:
$words = explode(' ',$str);
$exists_at = array_search($seach,$words);
if ($exists_at){
echo "Found at ".$exists_at." key in the \$word array";
}
In light of the pro-regex anti regex fight going on here, I must retract this answer and defer to the regex crowd, but I'm going to leave it up for historical record. I had always assumed that working with arrays was more efficient from a processing standpoint, but I decided to run some tests, and it turns out that my assumption was wrong. The result of a single word test:
Time to search for word 10000 times using in_array(): 0.011814
Time to search for word 10000 times using preg_match(): 0.001697
The code I used to test (which presumes that explode will be used each time):
$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";
$start = microtime(true);
for($i=0;$i<1000;$i++){
$words = explode(' ',$str);
if (in_array($search,$words)){
//
}
}
$end = microtime();
$total = $end-$start;
echo "Time to search for word 10000 times using in_array(): ";
echo $total;
echo "
";
$start = microtime(true);
for($i=0;$i<1000;$i++){
if (preg_match("/\b$search\b/", $str)) {
// word found
}
}
$end = microtime();
$total = $end-$start;
echo "Time to search for word 10000 times using preg_match(): ";
echo $total;
So conclusion: go with preg_match("/\b$search\b/", $str)