2015-04-01 63 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"; 
} 
相关问题