Check if array is inside string

$comment = 'billie jean is not my lover she is just a girl';
$words = array('jean','lover','jean');
$lin = some_function_name($comment,$words);
($lin=3)

I tried substr_count(), but it does not work in the array. Is there a built-in function for this?

+3
source share
5 answers

I would use array_filter().It will work in PHP> = 5.3. For the lower version, you will have to handle the callback differently.

$lin = sum(array_filter($words, function($word) use ($comment) {return strpos($comment, $word) !== false;}));
+2
source

This is a simpler approach with lots of lines of code:

function is_array_in_string($comment, $words)
{
    $count = 0;
    foreach ($comment as $item)
    {
        if (strpos($words, $item) !== false)
            count++;
    }
    return $count;
}

array_map is likely to produce much cleaner code.

+2
source

array_intersect explode:

:

count(array_intersect(explode(" ", $comment), $words)) == count($words)

:

count(array_unique(array_intersect(explode(" ", $comment), $words)))
+1

, downvoted regex , :

$hasword = preg_match('/'.implode('|',array_map('preg_quote', $words)).'/', $comment);
0

, ( PHP 5.3):

$comment = 'billie jean is not my lover she is just a girl';
$words = array('jean','lover','jean');
$lin = count(array_filter($words,function($word) use ($comment) {return strpos($comment,$word) !== false;})); 

:

$comment = 'billie jean is not my lover she is just a girl';
$words = array('jean','lover','jean');
$lin = count(array_intersect($words,explode(" ",$comment)));

In the second case, it will simply return, if there is a perfect match between the words, the substrings will not be considered.

0
source

Source: https://habr.com/ru/post/1721931/


All Articles