PHP:逐字逐句阅读?

7

我想逐个单词读取文件。目前为止,我已经能够使用fgets()一行一行地读取或读取指定数量的字节,但这并不是我想要的。我希望每次读取一个单词,直到下一个空格、\n或EOF。

有人知道如何在php中实现吗?在c++中,我只需要使用'cin >> 变量'命令。


1
请查看此链接 - http://www.phpbook.net/how-to-read-a-file-word-by-word-in-php.html - swapnesh
1
看这个:http://www.phpbook.net/how-to-read-a-file-word-by-word-in-php.html。哈哈,都是从同一个来源复制的 :P - Vivek Sadh
5个回答

4
你可以通过以下方式实现这一点:
$filecontents = file_get_contents('words.txt');

$words = preg_split('/[\s]+/', $filecontents, -1, PREG_SPLIT_NO_EMPTY);

print_r($words);

这将给您一个单词数组。

4
在这个话题中,对于一些回复,我想说:不要重复造轮子。 在PHP中使用:
str_word_count ( string $string [, int $format [, string $charlist ]] )

格式:

0 = 仅返回单词数量;

1 = 返回一个数组;

2 = 返回一个关联数组;

charlist:

Charlist是您认为是单词的字符。

Function.str-word-count.php

[注意]

没有人知道您的文件内容的大小,如果您的文件内容很大,则存在许多灵活的解决方案。

(^‿◕)


1
你需要使用fgetc逐个获取字母,直到遇到单词分界符,然后对该单词进行操作。示例:
 $fp = fopen("file.txt", "r");
 $wordBoundries = array("\n"," ");
 $wordBuffer = "";
 while ($c = fgetc($fp)){
     if (in_array($c, $wordBountries)){
         // do something then clear the buffer
         doSomethingWithBuffer($wordBuffer);
         $wordBuffer = "";
     } else {
        // add the letter to the buffer
        $wordBuffer.= $c;
     }
 }
 fclose($fp);

0
你可以尝试使用 fget() 函数,它可以逐行读取文件,当你从文件中获取一行时,你可以使用 explode() 函数来提取由空格分隔的单词。
尝试这段代码:
$handle = fopen("inputfile.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        // process the line read.
        $word_arr = explode(" ", $line); //return word array
        foreach($word_arr as $word){
            echo $word; // required output
        }
    }
    fclose($handle);
} else {
    // error while opening file.
    echo "error";
}

0
关于“不重复造轮子”,我同意。 PHP参考文档中对str_word_count ( string $string [, int $format [, string $charlist ]] )的说明如下:

“请注意,不支持多字节语言环境。”

如果需要此功能,可能会有其他建议可以应用。
$words = preg_split('/[\s]+/', $filecontents, -1, PREG_SPLIT_NO_EMPTY);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接