2017-03-01 84 views
0

我是一個php中的新手,所以,我正在製作一個字計數器程序。我試圖計算特定單詞在網站中的實例數量。 所以,我使用Substr_count來計算單詞的數量,但問題是它會像「陽光」一樣包含像「陽光」這樣的詞彙。substr_count()在php中計算整個單詞

這是我的代碼。

/*When the user types the word*/ 
$search = $_POST["texto"]; 

/*The website*/ 
$page = $_POST["Web"]; 

$web = file_get_contents($page); 

/*Count words*/ 
$result = (substr_count(strip_tags(strtolower($web)), strtolower($search))); 

/*Display the information*/ 
if($result == 0){ 
echo "the word " .mb_strtoupper($search). " doesn't appear";  
}else{ 
echo "the word " .mb_strtoupper($search). " appears $result times"; 
} 

有什麼辦法解決這個問題?我試過str_word_count和preg_match_all,但是這顯示大數字。

+1

計算機如何知道它只能選擇陽光而不是陽光?你可以在這個問題上添加一些樣本數據 –

+0

@Wolvy substr - 正好代表'sub' - 較小,較小(部分)和字符串......它沒有考慮到什麼「單詞」是 –

+0

@ Wolvy - 你應該考慮使用正則表達式代替 –

回答

0

這將做詭計:

/*Count words*/ 
$result = preg_match_all('/\b'. strtolower($search) .'\b/', strtolower($web)); 
+0

謝謝,您的解決方案 – Wolvy

+0

沒問題Wolvy – ded

0

我會用的str_word_count()組合讓所有的單詞和array_count_values()來算的次數這些話出現:

# Get an array with lowercase words 
$array_with_words = str_word_count(strtolower('string to analyze'), 1); 

# Get a count of all unique values 
$array_with_words_count = array_count_values($array_with_words); 

# Get the count of the word you are looking for 
$your_count = $array_with_words_count[ strtolower('your_word') ]; 
0

的str_word_cound($表達,1)函數會給你一個關聯數組用的話,那麼就可以使用foreach一次和構建具有詞頻率像這樣的陣列循環:

$expr = "My test expression. <b>My</b> world."; 
$words = str_word_count(strip_tags(strtolower($expr)), 1); 
$groupedWords = []; 
foreach ($words as $word) { 
    print_r($word); 
    $groupedWords[$word] ++; 
} 
print_r($groupedWords); 

將打印:

Array 
(
    [my] => 2 
    [test] => 1 
    [expression] => 1 
    [world] => 1 
) 

要檢查有多少次是用了一個詞:

var_dump(array_key_exists('specific_word_you_look_for', $groupedWords) ? $groupedWords['specific_word_you_look_for'] : false); 

// will output the frequency or false if not found 
-1

如果你想使用預定義功能,然後使用str_word_count()
例如:

<?php 
echo str_word_count("stack gives answer"); 
?> 

輸出: 3

+0

計算單詞的總數,而不是字符串中特定單詞出現的次數。 – jeroen