How to check if a word exists in a sentence

Tafu picture Tafu · Nov 10, 2011 · Viewed 11.6k times · Source

For example, if my sentence is $sent = 'how are you'; and if I search for $key = 'ho' using strstr($sent, $key) it will return true because my sentence has ho in it.

What I'm looking for is a way to return true if I only search for how, are or you. How can I do this?

Answer

codaddict picture codaddict · Nov 10, 2011

You can use the function preg-match that uses a regex with word boundaries:

if(preg_match('/\byou\b/', $input)) {
  echo $input.' has the word you';
}