繁体   English   中英

在PHP中编辑文件后删除空行

[英]remove empty line after edit file in php

我正在为我的网站创建一个文本站点地图,如下所示:

sitemap.txt:

https://example.com/
https://example.com/estate/showAll
https://example.com/estate/search
https://example.com/site/about
https://example.com/site/contact
https://example.com/post/show/41
https://example.com/post/show/42
https://example.com/post/show/43

当用户删除帖子42时,我的站点地图应更改为:

https://example.com/
https://example.com/estate/showAll
https://example.com/estate/search
https://example.com/site/about
https://example.com/site/contact
https://example.com/post/show/41
https://example.com/post/show/43

我尝试了这些方法,但是它们没有按预期工作:

$sitmap = file_get_contents('sitemap.txt');
$line   = 'https://example.com/post/show/42';
$sitmap =str_replace($line, '', $sitmap);
file_put_contents('sitemap.txt', $sitmap);

此代码在sitemap.txt中显示一个空行

$sitmap = file_get_contents('sitemap.txt');
$line   = 'https://example.com/post/show/42';
$sitmap =str_replace($line, '', $sitmap);
$sitmap =str_replace($line, chr(8), $sitmap);
file_put_contents('sitemap.txt', $sitmap);

chr(8)显示退格字符BS它不会删除空的换行符。

我已经用下面的代码完成了,但是我认为如果sitemap.txt变大,它将占用过多的内存

$sitmap = file_get_contents('sitemap.txt');
$line   = 'https://example.com/posst/show/'. $id;
$sitmap = explode(PHP_EOL, $sitmap);

if ($key = array_search($line, $sitmap)) {
     unset($sitmap[$key]);
}
$sitmap = implode(PHP_EOL, $sitmap);

file_put_contents('sitemap.txt', $sitmap);

有没有更好的办法?

您可以只替换行+换行符( \\n ):

$line = 'https://example.com/post/show/'. $id;
$file = 'sitemap.txt';
file_put_contents($file, 
    str_replace("$line\n", '', file_get_contents($file))
);

正如Nigel Ren指出的(请参阅下面的评论), "$line\\n"应该替换为$line.PHP_EOL

这取决于您如何构建文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM