我将这个array_diff用于两个文本,但我不能在文本行和文本行使用这些preg_replaces删除空行
$result = preg_replace('/^[ \t]*[\r\n]+/m', '', $result);
$result = preg_replace('/[\r\n]+$/', '', $result);
我不应该删除PHP.EOL,但它会显示一个空行。我该怎么办?
<?php
$new = explode(PHP_EOL, file_get_contents('new.txt').PHP_EOL);
$old = explode(PHP_EOL, file_get_contents('old.txt').PHP_EOL);
$result = array_diff($new, $old);
$output= fopen("Output.txt", "w") or die("Unable to open file!");
foreach($result as $value){
fwrite($output, $value.PHP_EOL); }
?>
output.txt的例子
4. data
3. data
2. data
1. blank line
答案 0 :(得分:1)
尝试不同的方法:
$new = file('new.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$old = file('old.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$result = array_diff($new, $old);
file_put_contents('Output.txt', implode(PHP_EOL, $result));
file()
剥离换行符FILE_IGNORE_NEW_LINES
并跳过空行FILE_SKIP_EMPTY_LINES
array_diff()
implode()
新行上的结果数组并将其写入输出文件