2017-04-16 82 views
1

我有一个原来有一个空Righa开头和两个空行翼端文件空行产生了我一个错误删除文本文件

<?php 
$file = "https://example.com/text/file.txt"; 

$fr = fopen($file, 'r'); 

$contenuto = ""; 
while (!feof($fr)) { 

    $riga = fgets($fr); 

    $inizio = strpos($riga, "Capitolo"); 

    $nuova_riga = substr($riga, $inizio); 

    $contenuto .= $nuova_riga . ""; 
} 
fclose($fr); 
$fr = fopen("file.txt", 'w'); 
fwrite($fr, $contenuto); 
fclose($fr); 

注意:未定义抵消: 注意:未定义指数:

如果手动删除空行显然我没有错,所以我应该打开一个只写取消空白行,然后用页面上的其他指令继续在文件。我能怎么做?谢谢

+0

哪里是你的代码的兄弟? –

回答

3

没有完全理解你的问题。也许是这样?

str_replace("\n\n", "\n", $file) 
0

你可以这样使用它。

<?php 
ini_set('display_errors', 1); 
$resultant=array(); 
$lines=file("/path/to/your/test.txt");//retrieving lines of the file. 

foreach($lines as $value) 
{ 
    if($value!="\n") 
    { 
     $resultant[]=$value; 
    } 
} 

$string=implode("", $resultant);//combining array into string with null 
file_put_contents("/path/wher/you/want/to/save.txt", $string); 
+0

这样不会删除空行,但添加行和其他 – Michael

+0

@迈克尔我已经更新了我的文章,你可以检查它会正常工作之间的空行。我已经测试过它。 –

+0

它不工作,所以在一开始的空行,并最终留在记事本++展望看到行包含CR和LF可能消除这些 – Michael

0

试试这个支持标志的file function

file_put_contents('file.txt',implode('', file('https://example.com/text/file.txt', FILE_SKIP_EMPTY_LINES)));