$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