PHP:逐字阅读?
我试图一次读一个字的文件。到目前为止,我已经能够使用fgets()逐行或最多读取一定数量的字节,但这不是我想要的。我一次只想说一句话。直到下一个空白、\n或EOF 有人知道如何在php中实现这一点吗。在C++中,我只使用了“CIN > var”命令。 可以通过来实现。PHP:逐字阅读?,php,file,parsing,Php,File,Parsing,我试图一次读一个字的文件。到目前为止,我已经能够使用fgets()逐行或最多读取一定数量的字节,但这不是我想要的。我一次只想说一句话。直到下一个空白、\n或EOF 有人知道如何在php中实现这一点吗。在C++中,我只使用了“CIN > var”命令。 可以通过来实现。 $filecontents = file_get_contents('words.txt'); $words = preg_split('/[\s]+/', $filecontents, -1, PREG_SPLIT_NO_EM
$filecontents = file_get_contents('words.txt');
$words = preg_split('/[\s]+/', $filecontents, -1, PREG_SPLIT_NO_EMPTY);
print_r($words);
这将为您提供一系列单词以获得本主题中的一些回复:我说:不要重新发明轮子。 在PHP中使用:
str_word_count ( string $string [, int $format [, string $charlist ]] )
格式:
0=仅返回字数
1=返回一个数组
2=返回关联数组
字符列表:
str_word_count ( string $string [, int $format [, string $charlist ]] )
字符是你认为一个词的字符。
[注意]
没有人知道文件内容的大小,如果文件内容很大,则存在许多灵活的解决方案
(二)◕) 您必须使用fgetc一次获取一个字母,直到您找到一个单词bountry,然后对该单词进行处理。例如
$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);
您可以尝试使用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";
}
检查此项-查看此项:-.Lol所有副本均来自同一源:P