我有一个txt文件,它的内容像这样:
Hello
World
John
play
football
我想在读取此文本文件时删除换行符,但我不知道它是什么样子的,
该文件是.txt格式且编码为utf-8。我想删除读取这个文本文件时的换行字符,但是我不知道这个换行字符长什么样子, 这个文件的格式是 .txt,编码为 utf-8。
我有一个txt文件,它的内容像这样:
Hello
World
John
play
football
我想在读取此文本文件时删除换行符,但我不知道它是什么样子的,
该文件是.txt格式且编码为utf-8。只需使用带有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)
。这样可以跳过空的新行! - Derk Jan Speelman换行符有不同的种类。这将从$string
中删除所有3种类型的换行符:
$string = str_replace(array("\r", "\n"), '', $string)
\r
,\n
和\r\n
),而我回答中的脚本可以处理这3种情况。 - Alex Turpin$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";