PHP 爆炸函数与 file_get_contents?
<?php
$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>
上面的代码打印一个数组作为输出。
如果我使用
<?php
$homepage = file_get_contents('http://www.example.com/data.txt');
print_r (explode(" ",$homepage));
?>
但是它不会以数组的形式显示文本文件中的各个数字。
最终我想从文本文件中读取数字并打印它们的频率。 data.txt 有 100,000 个数字。每行一个数字。
<?php
$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>
The above code prints an array as an output.
If I use
<?php
$homepage = file_get_contents('http://www.example.com/data.txt');
print_r (explode(" ",$homepage));
?>
However it does not display individual numbers in the text file in the form of an array.
Ultimately I want to read numbers from a text file and print their frequency. The data.txt has 100,000 numbers. One number per line.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
新行不是空格。您必须在适当的换行字符组合处爆炸。例如,对于 Linux:
或者,您可以使用
preg_split
和匹配每个空白字符的字符组\s
:另一个选项(可能更快)可能是使用
fgetcsv
。A new line is not a space. You have to explode at the appropriate new line character combination. E.g. for Linux:
Alternatively, you can use
preg_split
and the character group\s
which matches every white space character:Another option (maybe faster) might be to use
fgetcsv
.如果您希望文件的内容作为行数组,已经有一个内置函数
请参见手册:file()< /a>
If you want the content of a file as an array of lines, there is already a built-in function
See Manual: file()
尝试在“\n”处爆炸
另请参阅:
http://php.net/手册/de/function.file.php
Try exploding at "\n"
Also have a look at:
http://php.net/manual/de/function.file.php
您也可以通过使用正则表达式来解决它:
这将为您提供变量 $matches,其中包含一个带有数字的数组。这将确保它只会检索其中包含数字的行,以防文件格式不正确。
You could solve it by using a Regexp also:
This will give you the variable $matches which contains an array with numbers. This will ensure it will only retrieve lines that have numbers in them in case the file is not well formatted.
您没有使用正确的字符来分解字符串。您需要在新行分隔符 (
\n
) 上分解或使用正则表达式(会更慢但更健壮)。在这种情况下,请使用 preg_splitYou are not exploding the string using the correct character. You either need to explode on new line separator (
\n
) or use a regular expression (will be slower but more robust). In that case, use preg_split