views:

212

answers:

7
$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 doesn't work on array. Is there a builtin function to do this?

Thanks!!

A: 

You might see if array_map will do what you want.

Myles
A: 

You may wish to check out: http://uk2.php.net/manual/en/function.array-walk-recursive.php

Lizard
+2  A: 

I would use array_filter(). This will work in PHP >= 5.3. For a lower version, you'll need to handle your callback differently.

$lin = sum(array_filter($words, function($word) {return strpos($comment, $word) !== false;}));
Jeremy DeGroot
+1  A: 

This is a simpler approach with more 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 would probably produce a much cleaner code.

rogeriopvl
+1  A: 

using array_intersect & explode:

to check all there:

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

count:

count(array_unique(array_intersect(explode(" ", $comment), $words)))
najmeddine
Wouldn't this unnecessarily guzzle memory? (exploding the entire comment string.)
brianreavis
najmeddine
A: 

I wouldn't be surprised if I get downvoted for using regex here, but here's a one-liner route:

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

You can do it using a closure (works just with 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;}));

Or in a simpler way:

$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 way it will just return if there's a perfect match between the words, substrings won't be considered.

Felipe Ribeiro