2012-09-08 95 views
0

我正在對一些文本進行排序,我想要統計某個單詞出現的次數。php長度或計數字符串

文字部分我不想法,你有一些想法,我們將制定出一些 想法,我也沒想法,你有一些想法,我們將制定一些想法,我沒有想法,你有一些想法,我們將努力 一些想法

我如何使用PHP來算多少次「想法」發生,就像詞「想法」發生 我在數量和長度困惑。

有人可以舉個例子嗎?非常感謝

+1

你需要數_words_或_substrings_嗎?例如,「理想主義」中的「觀念」也應該計算在內嗎?如果'是',請在'substr_count'之間選擇提供答案。 )否則,請考慮使用'str_word_count'或其正則表達式。 – raina77ow

回答

4

請嘗試下面的腳本。 str_word_count()會將句子拆分爲單詞數組,array_count_values()將分配每個單詞出現的次數。

$words = str_word_count($text, 1); 
$times = array_count_values($words); 
echo $times['idea']; 
0

使用像搜索突出法(修改,以自己的方式工作)

<?php 
$s = 'idea'; 
$text = "I have no idea, you got some idea, we will work out some idea, I have no idea, you got some idea, we will work out some idea, I have no idea,you got some idea, we will work out some idea"; 
$keys = explode(" ",$s); 
$count = preg_match_all('/('. implode('|', $keys) .')/iu', $text); 
echo $count; 
?> 

相較於substr_count功能,這會算 'ideaidea' 兩個。