$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()
,但它不适用于数组。是否有内建功能来做到这一点?检查数组是否在一个字符串内
$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()
,但它不适用于数组。是否有内建功能来做到这一点?检查数组是否在一个字符串内
我会使用array_filter().
这将工作在PHP> = 5.3。对于较低版本,您需要以不同的方式处理回调。
$lin = sum(array_filter($words, function($word) use ($comment) {return strpos($comment, $word) !== false;}));
这是多行代码更简单的方法:
function is_array_in_string($comment, $words)
{
$count = 0;
foreach ($comment as $item)
{
if (strpos($words, $item) !== false)
count++;
}
return $count;
}
array_map可能会产生一个更干净的代码。
使用array_intersect
& explode
:
检查所有有:
count(array_intersect(explode(" ", $comment), $words)) == count($words)
计数:
count(array_unique(array_intersect(explode(" ", $comment), $words)))
这不会不必要地引起内存? (爆炸整个注释字符串。) – brianreavis 2009-11-04 21:48:31
因为我们正在搜索单词,所以我想在搜索之前将$注释转换为单独的单词(空格分隔)。否则,通过strpos&co功能,在'billie jean'和'billiejean'中将会找到'jean' – manji 2009-11-04 22:19:14
,我不会感到惊讶,如果我得到downvoted这里使用正则表达式,但这里是一条航线:
$hasword = preg_match('/'.implode('|',array_map('preg_quote', $words)).'/', $comment);
您可以使用闭合(工作只是用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)));
在第二种方式中,将刚刚返回,如果有一个字之间的完美匹配,子串将不被考虑。
'some_function_name'应该返回来自'$ words'的匹配字符串吗? – 2009-11-04 21:40:15
我想他想知道数组中的所有项目是否都在提供的字符串中? – 2009-11-04 22:10:11