Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a word exists in a sentence

Tags:

php

search

strstr

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?

like image 756
Tafu Avatar asked Nov 10 '11 04:11

Tafu


2 Answers

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';
}
like image 139
codaddict Avatar answered Oct 20 '22 07:10

codaddict


If you want to check for multiple words in the same string, and you're dealing with large strings, then this is faster:

$text = explode(' ',$text);
$text = array_flip($text);

Then you can check for words with:

if (isset($text[$word])) doSomething();

This method is lightning fast.

But for checking for a couple of words in short strings then use preg_match.

UPDATE:

If you're actually going to use this I suggest you implement it like this to avoid problems:

$text = preg_replace('/[^a-z\s]/', '', strtolower($text));
$text = preg_split('/\s+/', $text, NULL, PREG_SPLIT_NO_EMPTY);
$text = array_flip($text);

$word = strtolower($word);
if (isset($text[$word])) doSomething();

Then double spaces, linebreaks, punctuation and capitals won't produce false negatives.

This method is much faster in checking for multiple words in large strings (i.e. entire documents of text), but it is more efficient to use preg_match if all you want to do is find if a single word exists in a normal size string.

like image 6
Alasdair Avatar answered Oct 20 '22 09:10

Alasdair