2017-01-04 50 views
0

我似乎無法找到任何解決以下問題的東西,並認爲我會尋求幫助。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」

等等

非常感謝

詹姆斯

回答

0

你只是增加計數器,如果有匹配,而不是匹配的數量。使用preg_match_all並計算匹配結果的數量。

$ string ='查看找到所有停用詞的次數的字符串,必須包含短語並返回所有停用詞的數組以及每次停用詞的次數。

// 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_all($pattern, $string, $matches)) { 
      $counter += count($matches[0]); 
     } 
    } 
    return $counter; 
} 

// test - output counter only 
echo counter_words($string, $stopwords); 

演示:https://eval.in/709349

你也可以用|implode$stopwords如果有永遠不會在那裏一個特殊字符,那麼你不需要foreach

....

或對每個匹配的項的計數(這也使用implode方法)。

$ string ='查看找到所有停用詞的次數的字符串,必須包含短語並返回所有停用詞的數組以及每次停用詞的次數。

// test stopwords 
$stopwords = array('all','times','words are found'); 

function counter_words($string, $stopwords) { 
    $pattern = '/\b' . implode('|', $stopwords) . '\b/i'; 
    preg_match_all($pattern, $string, $matches); 
    return !empty($matches) ? array_count_values($matches[0]) : 'No matches found'; 
} 

// test - output counter only 
print_r(counter_words($string, $stopwords)); 

演示:https://eval.in/709369

+0

嗨@ chris85感謝您的回覆速度快,這幾乎就是我了。你能告訴我如何返回一個關聯數組,其中包含找到的每個停用詞和它的計數器值嗎? –

+0

哦,錯過了,好的,更新...如果這回答了這個問題,請記住接受它。 – chris85

+0

omg,你不知道我一直在努力做多久,大聲笑......非常感謝你!我非常感謝幫助和示例 –

0

檢查了這一點。它將返回櫃檯在單個陣列中的所有單詞:

$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'; 


$stopwords = array('all','times','words are found'); 

function counter_words($string, $stopwords) { 
    $output = array(); 

    foreach ($stopwords as $stopword) { 
     $pattern = '/\b' . $stopword . '\b/i'; 
     preg_match_all($pattern, $string, $matches); 
     $output[$stopword] = count($matches[0]); 
    } 
    return $output; 
} 

echo '<pre>';print_r(counter_words($string, $stopwords));exit; 

測試這裏https://eval.in/709375

+0

謝謝@SD,這也是一種享受! –

相關問題