3
$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?

2
  • 1
    Is some_function_name supposed to return how many strings from $words were matched? Commented Nov 4, 2009 at 21:40
  • i think he wants to know if all items in the array are in the string provided? Commented Nov 4, 2009 at 22:10

5 Answers 5

2

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;}));
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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

2 Comments

Wouldn't this unnecessarily guzzle memory? (exploding the entire comment string.)
because we're searching for words, I thought of transforming the $comment to separate words (space delimited) before the search. Otherwise, with strpos & co functions, 'jean' will be found in 'billie jean' & 'billiejean'
0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.