简体   繁体   English

PHP如何编辑和删除txt文件中的行

[英]PHP How to EDIT And Delete line in txt file

I have one CFG file so i need to edit and delete lines...i have using this code but it does not replace line. 我有一个CFG文件,所以我需要编辑和删除行...我已经在使用此代码,但它不能代替行。

/* check if user exists */
$delete = "F: $username $password # { startdate=$today | enddate=$expired | info=$info | dealer=$dealer }";
$out = array();
while (($line = fgets($stream)) !== false) {
     if(trim($line) != $delete) {
        /* user already exists - we can edit it */
        $out[] = $line;
    }
}

/* write file */
$sftp = ssh2_sftp($con);
$stream = fopen("ssh2.sftp://$sftp/myurl/config/txtfile.cfg", 'w+') or die("can't open file");
flock($stream, LOCK_EX);
foreach($out as $line) {
    fwrite($stream, $line);
}
flock($stream, LOCK_UN);
fclose($stream);

I have 100 lines in that txt file and i have send this with ajax: 我在该txt文件中有100行,并且已使用ajax发送:

F: lolipop shugar # { startdate=2015-08-04 | F:lolipop shugar#{startdate = 2015-08-04 | enddate=2016-08-04 | enddate = 2016-08-04 | info=informations | info =信息| dealer=current dealer } 经销商=当前经销商}

so after writing back to txt cfg file it needs to be written 99 lines without line that begins F: lolipop...so that line is deletet (then i can implement edit line...the idea is to delete line with F: knowusername and then insert new one with new data) 所以写回txt cfg文件后,需要写成99行,而没有以F开始的行:lolipop ...以便删除该行(然后我可以实现编辑行...这个想法是用F:knowusername删除行然后插入新的新数据)

I have try this...file is read correctly into array but file is not written back to txt cfg files with changes...i have txt cfg file that is unchanged with 100lines...could someone post solution? 我已经尝试过...文件已正确读取到数组中,但文件没有更改后写回到txt CFG文件中...我有100行没有变化的txt CFG文件...有人可以发布解决方案吗?

Thanks 谢谢

Example: 例:

i have in file: 我有档案:

F: user010 sdfsdfsdf # { startdate=$today | enddate=$expired | info=$info | dealer=$dealer }
F: huikkd rrrrr # { startdate=$today | enddate=$expired | info=$info | dealer=$dealer }
F: robot56 uxDtpNjf # { startdate=$today | enddate=$expired | info=$info | dealer=$dealer }

so i want to find line: 所以我想找到行:

F: huikkd rrrrr # { startdate=$today | enddate=$expired | info=$info | dealer=$dealer }

and edit it to: 并将其编辑为:

F: huikkd changedpassword # { startdate=$today | enddate=$expired | info=$info | dealer=$dealer }

and write it back to cfg file..i im saving file on server throught ssh2 connection 并将其写回cfg file..i,通过ssh2连接将文件保存在服务器上

You will be able to edit any line of cfg file. 您将能够编辑cfg文件的任何行。 Do not remove \\n . 请勿删除\\n Just edit the text before \\n . 只需编辑\\n之前的文本即可。 Hope this code will help: 希望这段代码对您有所帮助:

<?php
$line=file('text.cfg',FILE_SKIP_EMPTY_LINES);
$line[4]="jhasrd ady"."\n";//This will edit line 4 with text jhasrd ady
$content=implode('',$line);
file_put_contents('text.cfg',$content);

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

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