php PHP用file_get_contents爆炸函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5855740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP explode function with file_get_contents?
提问by KingCrunch
<?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.
最终我想从文本文件中读取数字并打印它们的频率。data.txt 有 100,000 个数字。每行一个号码。
回答by Felix Kling
A new line is not a space. You have to explode at the appropriate new line character combination. E.g. for Linux:
新行不是空格。您必须在适当的新行字符组合处爆炸。例如对于 Linux:
explode("\n",$homepage)
Alternatively, you can use preg_split
and the character group \s
which matches every white space character:
或者,您可以使用preg_split
和\s
匹配每个空白字符的字符组:
preg_split('/\s+/', $homepage);
Another option (maybe faster) might be to use fgetcsv
.
另一种选择(可能更快)可能是使用fgetcsv
.
回答by KingCrunch
If you want the content of a file as an array of lines, there is already a built-in function
如果你想要一个文件的内容作为一个行数组,已经有一个内置函数
var_dump(file('http://www.example.com/data.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
See Manual: file()
回答by Yoshi
Try exploding at "\n"
尝试在“\n”爆炸
print_r (explode("\n",$homepage));
Also have a look at:
也看看:
回答by rzetterberg
You could solve it by using a Regexp also:
您也可以通过使用正则表达式来解决它:
$homepage = file_get_contents("http://www.example.com/data.txt");
preg_match_all("/^[0-9]+$/", $homepage, $matches);
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.
这将为您提供包含数字数组的变量 $matches。这将确保它只会在文件格式不正确的情况下检索包含数字的行。
回答by Vincent Mimoun-Prat
You 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
您没有使用正确的字符分解字符串。您要么需要在新行分隔符 ( \n
)上爆炸,要么使用正则表达式(会更慢但更健壮)。在这种情况下,使用preg_split