2015-04-01 28 views
0

我需要一些幫助。如何使用PHP計算文本文件中每個單詞的長度。例如PHP如何計算文本文件中每個單詞的長度

。有test.txt。而遏制是「大家好,我需要一些幫助。」 如何輸出文本,然後計算每個單詞的長度,如:

陣列

hello => 5 
everyone => 8 
i => 1 
need => 4 
some => 4 
help => 4 

我剛開始學習PHP。所以請詳細解釋你所寫的代碼的細節。

千恩萬謝

+1

讀文件 - >過濾器逗號,點等 - >使用爆炸($ filteredfile,'‘) – Jordy 2015-04-01 12:07:12

回答

0

這應該工作

$text = file_get_contents('text.txt'); // $text = 'hello everyone, i need some help.'; 
$words = str_word_count($text, 1); 
$wordsLength = array_map(
    function($word) { return mb_strlen($word, 'UTF-8'); }, 
    $words 
); 

var_dump(array_combine($words, $wordsLength)); 

欲瞭解更多信息有關str_word_count及其參數見http://php.net/manual/en/function.str-word-count.php

基本上,一切都在php.net很好的描述。 array_map函數遍歷給定的數組,並對該數組中的每個項應用給定的(例如,匿名)函數。函數array_combine通過使用一個數組作爲鍵和另一個數組的值來創建一個數組。

+0

你到了那裏漂亮的代碼,它只是缺少’如何閱讀文件'部分。除此之外,不錯的工作。 – Jordy 2015-04-01 12:15:33

+0

@Jordy謝謝,我添加了file_get_contents到我的答案 – 2015-04-01 12:24:42

0

如果您不需要後處理的話長度,試試這個:

// Get file contents 
$text = file_get_contents('path/to/file.txt'); 

// break text to array of words 
$words = str_word_count($text, 1); 

// display text 
echo $text, '<br><br>'; 

// and every word with it's length 
foreach ($words as $word) { 
    echo $word, ' => ', mb_strlen($word), '<br>'; 
} 

但注意到,該str_word_count()功能與UTF-8字符串(FE波蘭,捷克和類似的許多問題字符)。如果你需要這些,那麼我建議過濾出逗號,點和其他非單詞字符,並使用explode()來獲得$words數組。

0

這是工作

$stringFind="hello everyone, i need some help"; 

$file=file_get_contents("content.txt");/*put your file path */ 

$isPresent=strpos($file,$stringFind); 
if($isPresent==true){ 
$countWord=explode(" ",$stringFind); 
foreach($countWord as $val){ 
echo $val ." => ".strlen($val)."<br />"; 
} 
}else{ 
echo "Not Found"; 
} 
相關問題