【发布时间】:2012-04-13 03:40:21
【问题描述】:
我有一个txt文件,它的内容是这样的
Hello
World
John
play
football
我想在阅读这个文本文件时删除换行符,但我不知道它是什么样子 文件 .txt,其编码为 utf-8
【问题讨论】:
-
Mira,你想用什么都没有替换,还是用其他类型的空格?
标签: php newline text-files
我有一个txt文件,它的内容是这样的
Hello
World
John
play
football
我想在阅读这个文本文件时删除换行符,但我不知道它是什么样子 文件 .txt,其编码为 utf-8
【问题讨论】:
标签: php newline text-files
只需使用带有FILE_IGNORE_NEW_LINES 标志的file 函数。
file 读取整个文件并返回一个包含所有文件行的数组。
默认情况下,每一行的末尾都包含换行符,但我们可以通过FILE_IGNORE_NEW_LINES 标志强制修剪。
所以很简单:
$lines = file('file.txt', FILE_IGNORE_NEW_LINES);
结果应该是:
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"
}
【讨论】:
$lines = file('file.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)。这样你也可以跳过空的新行!
如果您要将行放入数组中,假设文件大小合理,您可以尝试这样的事情。
$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
)
*/
【讨论】:
我注意到它在问题中的粘贴方式,这个文本文件似乎在每行的末尾都有空格字符。我会认为那是偶然的。
<?php
// Ooen the file
$fh = fopen("file.txt", "r");
// Whitespace between words (this can be blank, or anything you want)
$divider = " ";
// Read each line from the file, adding it to an output string
$output = "";
while ($line = fgets($fh, 40)) {
$output .= $divider . trim($line);
}
fclose($fh);
// Trim off opening divider
$output=substr($output,1);
// Print our result
print $output . "\n";
【讨论】:
trim 不是一个好的选择,如果 - 就足够了使用 rtrim (您只需要修剪右侧) - 不要忘记第二个参数,它是一个字符掩码。默认情况下,它将修剪:空格、制表符、新行、回车、空字节和垂直制表符。
有不同种类的换行符。这将删除 $string 中的所有 3 种:
$string = str_replace(array("\r", "\n"), '', $string)
【讨论】:
\r、\n 和 \r\n),我的答案中的脚本负责 3。