Mir*_*ira 9 php newline text-files
我有txt文件这样的内容
Hello
World
John
play
football
Run Code Online (Sandbox Code Playgroud)
我想在读取这个文本文件时删除新的行字符,但我不知道它看起来像文件.txt,它的编码是utf-8
abu*_*uba 14
只需使用file带FILE_IGNORE_NEW_LINES标志的功能.
在file读取整个文件并返回一个数组包含的所有文件中的行.
默认情况下,每一行都包含新行字符,但我们可以通过FILE_IGNORE_NEW_LINES标志强制修剪.
所以它将简单地说:
$lines = file('file.txt', FILE_IGNORE_NEW_LINES);
Run Code Online (Sandbox Code Playgroud)
结果应该是:
var_dump($lines);
array(5) {
[0] => string(5) "Hello"
[1] => string(5) "World"
[2] => string(4) "John"
[3] => string(4) "play"
[4] => string(8) "football"
}
Run Code Online (Sandbox Code Playgroud)
Ale*_*pin 10
有不同类型的换行符.这将删除所有3种$string:
$string = str_replace(array("\r", "\n"), '', $string)
Run Code Online (Sandbox Code Playgroud)
如果您要将行放入数组中,假设文件大小合理,您可以尝试这样的操作。
$file = 'newline.txt';
$data = file_get_contents($file);
$lines = explode(PHP_EOL, $data);
/** Output would look like this
Array
(
[0] => Hello
[1] => World
[2] => John
[3] => play
[4] => football
)
*/
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19801 次 |
| 最近记录: |