PHP如何计算文本文件中每个单词的长度

PHP如何计算文本文件中每个单词的长度,php,string,Php,String,我需要一些帮助。如何使用PHP计算文本文件中每个单词的长度 比如说。这里有test.txt。内容是“大家好,我需要帮助。” 如何输出文本,然后计算每个单词的长度,如: 排列 我刚开始学习php。所以请解释一下你写的代码的细节 非常感谢这应该行得通 $text = file_get_contents('text.txt'); // $text = 'hello everyone, i need some help.'; $words = str_word_count($text, 1); $wor

我需要一些帮助。如何使用PHP计算文本文件中每个单词的长度

比如说。这里有test.txt。内容是“大家好,我需要帮助。” 如何输出文本,然后计算每个单词的长度,如:

排列

我刚开始学习php。所以请解释一下你写的代码的细节

非常感谢这应该行得通

$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_计数及其参数的更多信息,请参阅


基本上,php.net对所有内容都有很好的描述。函数array_map遍历给定的数组,并对该数组中的每个项应用给定(例如匿名)函数。函数array\u combine使用一个数组作为键,另一个数组作为值来创建数组。

如果以后不需要处理单词的长度,请尝试以下操作:

// 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>';
}
//获取文件内容
$text=file_get_contents('path/to/file.txt');
//将文本拆分为单词数组
$words=str_word_count($text,1);
//显示文本
回显$text,“

”; //每个字都有它的长度 foreach($words作为$word){ echo$word,'=>',mb_strlen($word),“
”; }
但请注意,
str\u word\u count()
函数在UTF-8字符串(如波兰语、捷克语和类似字符)方面存在许多问题。如果您需要这些字符,那么我建议过滤掉逗号、点和其他非单词字符,并使用
explode()
获取
$words
数组。

这很有效

 $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";
}
$stringFind=“大家好,我需要帮助”;
$file=文件获取内容(“content.txt”)/*把你的文件路径*/
$isPresent=strpos($file,$stringFind);
如果($isPresent==true){
$countWord=explode(“,$stringFind”);
foreach($countWord作为$val){
echo$val.“=>”.strlen$val.“
”; } }否则{ 回声“未找到”; }
读取文件-->过滤逗号、圆点等-->使用explode($filteredfile,')这里的代码很漂亮,只是缺少了“如何读取文件”部分。除此之外,干得好。@Jordy谢谢,我在答案中添加了文件内容
 $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";
}