开发者

Check if array is inside a string

开发者 https://www.devze.com 2022-12-10 18:27 出处:网络
$comment = \'billie jean is not my lover she is just a girl\'; $words = array(\'jean\',\'lover\',\'jean\');
$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(),开发者_如何学JAVA but it doesn't work on array. Is there a builtin function to do this?


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


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.


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号