我似乎無法找到任何解決以下問題的東西,並認爲我會尋求幫助。PHP計數器返回所有停用詞和它們被發現多少次?
我正在嘗試檢索一個字符串中所有停用詞(包括短語匹配詞)的數組,以及每次找到多少次。下面的代碼是我最近的代碼,它將爲找到的停用詞的總數返回一個$計數器值(僅限單實例,但不是多個計數),並且顯然不會列出這些詞。
我已經嘗試使用preg_match_all和各種陣列輸出,並導致所有「頭抓」錯誤。
任何幫助,將不勝感激。
// test string
$string = 'a string to see how many times all stopwords words are found, must include phrases and return an array of all stopwords and how many times each was found';
// test stopwords
$stopwords = array('all','times','words are found');
function counter_words($string, $stopwords) {
$counter = 0;
foreach ($stopwords as $stopword) {
$pattern = '/\b' . $stopword . '\b/i';
if (preg_match($pattern, $string)) {
$counter++;
}
}
return $counter;
}
// test - output counter only
echo counter_words($string, $stopwords);
經過一些修改,我希望能夠返回一個數組(大概是一個關聯數組),我可以附和了類似的東西:找到
詞/詞組:「話是發現」 ,實例發現 「1」
詞/短語的形式出現: 「次」,實例發現 「1」
等等
非常感謝
詹姆斯
嗨@ chris85感謝您的回覆速度快,這幾乎就是我了。你能告訴我如何返回一個關聯數組,其中包含找到的每個停用詞和它的計數器值嗎? –
哦,錯過了,好的,更新...如果這回答了這個問題,請記住接受它。 – chris85
omg,你不知道我一直在努力做多久,大聲笑......非常感謝你!我非常感謝幫助和示例 –