Just split the line:
$words = explode(' ',$str); if (in_array($search,$words)){ echo "FOUND!"; }
Or if you need a place:
$words = explode(' ',$str); $exists_at = array_search($seach,$words); if ($exists_at){ echo "Found at ".$exists_at." key in the \$word array"; }
edits:
In light of the pro-regex regex struggle going on here, I have to cancel this answer and put aside the crowd of regexes, but I'm going to leave it to record the story. I always thought that working with arrays was more efficient in terms of processing, but I decided to conduct some tests, and it turned out that my assumption was wrong. Single word test result:
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 assumes that explode will be used every 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 "<br />"; $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 to preg_match ("/ \ b $ search \ b /", $ str)
Ben d source share