[英]How to replace a line with another line in PHP using its number
hope that you're doing well, I'm trying to implement a script so that I can use it to replace a line with another one in a file, I tried a lot of PHP scripts and Bash codes but they all seem to failed, here what I tried last:希望你做得很好,我正在尝试实现一个脚本,以便我可以使用它来替换文件中的另一行,我尝试了很多 PHP 脚本和 Bash 代码,但它们似乎都失败了,这是我最后尝试的:
function replace_a_line() {
$line=3; //includes zero as 1.
$newdata='this is a test 123';
$data=file('./txt.txt');
$data[$line]=$newdata."\r\n";
$data=implode($data);
file_put_contents('./txt.txt',$data);
}
My file name is txt.txt我的文件名是txt.txt
Thank you in advance先感谢您
I think you almost did it.我想你几乎做到了。 No need to implode it yourself.
无需自己内爆。
file_put_contents
does it for you.file_put_contents
为您完成。 Add additional checks to make sure line number is something within the number of lines range or append the text to the end.添加额外的检查以确保行号在行数范围内或 append 文本到末尾。
<?php
function replace_a_line($line = 3,$new_str = 'Your text') {
$data = file('test.txt');
if($line >= count($data)) $data[] = $new_str;
else $data[ $line - 1] = $new_str . "\n";
return file_put_contents('test.txt', $data, LOCK_EX);
}
replace_a_line();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.