$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)
我尝试substr_count()
,但它不适用于数组。是否有内置函数来执行此操作?
答案 0 :(得分:2)
我会使用array_filter().
这将在PHP> = 5.3中使用。对于较低版本,您需要以不同方式处理回调。
$lin = sum(array_filter($words, function($word) use ($comment) {return strpos($comment, $word) !== false;}));
答案 1 :(得分:2)
这是一种更简单的方法,包含更多代码:
function is_array_in_string($comment, $words)
{
$count = 0;
foreach ($comment as $item)
{
if (strpos($words, $item) !== false)
count++;
}
return $count;
}
array_map可能会产生更清晰的代码。
答案 2 :(得分:1)
使用array_intersect
& explode
:
检查那里:
count(array_intersect(explode(" ", $comment), $words)) == count($words)
数:
count(array_unique(array_intersect(explode(" ", $comment), $words)))
答案 3 :(得分:0)
如果我在这里使用正则表达式,我不会感到惊讶,但这是一条单行路线:
$hasword = preg_match('/'.implode('|',array_map('preg_quote', $words)).'/', $comment);
答案 4 :(得分: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)));
在第二种方式中,如果单词之间存在完美匹配,它将返回,不会考虑子串。