Gal
Gal

Reputation: 23662

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

Upvotes: 3

Views: 1103

Answers (5)

Jeremy DeGroot
Jeremy DeGroot

Reputation: 4506

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) use ($comment) {return strpos($comment, $word) !== false;}));

Upvotes: 2

Felipe Ribeiro
Felipe Ribeiro

Reputation: 374

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.

Upvotes: 0

brianreavis
brianreavis

Reputation: 11546

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);

Upvotes: 0

rogeriopvl
rogeriopvl

Reputation: 54056

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.

Upvotes: 2

manji
manji

Reputation: 47978

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)))

Upvotes: 1

Related Questions