What is best way to search a text to determine if it contains the word (or words) I am searching for?
If it was just searching for a single word, it would have been easy, but the needle can be a word or more than a word.
Example
$text = "Dude,I am going to watch a movie, maybe 2c Rio 3D or Water for Elephants, wanna come over";
$words_eg1 = array ('rio 3d', 'fast five', 'sould surfer');
$words_eg2 = array ('rio', 'fast five', 'sould surfer');
$words_eg3 = array ('Water for Elephants', 'fast five', 'sould surfer');
'
is_words_in_text ($words_eq1, $text) / true, 'Rio 3D' matches with 'rio 3d'
is_words_in_text ($words_eq2, $text) //true, 'Rio' matches w开发者_JS百科ith 'rio'
is_words_in_text ($words_eq3, $text) //true, 'Water for Elephants'
Thank you,
In your case stripos()
will probably do the trick:
function is_words_in_text($words, $string)
{
foreach ((array) $words as $word)
{
if (stripos($string, $word) !== false)
{
return true;
}
}
return false;
}
But this will match also non-words (as in te
in Water
), to fix this we can use preg_match()
:
function is_words_in_text($words, $string)
{
foreach ((array) $words as $word)
{
if (preg_match('~\b' . preg_quote($word, '~') . '\b~i', $string) > 0)
{
return true;
}
}
return false;
}
All searches are done in a case-insensitive way, $words
can either be a string or an array.
You could iterate over the elements of $words_eg1, 2, 3 and stop as soon as strpos
or strstr
returns a non-false value.
精彩评论