gpt4 book ai didi

php - 如何在 PHP 中转换我的 sed 插入文本脚本?

转载 作者:行者123 更新时间:2023-12-04 18:45:51 25 4
gpt4 key购买 nike

我有一个有效的 sed 脚本,可以在行号处将文本插入到文档中。

sed -i '35i \ NewPage,' file

想知道是否有一种方法可以使用 php 获得相同的结果。
35 i 是要插入的行号
\在新行中插入
NewPage 是要插入的文本
文件是文件位置

有什么建议么?
此致
在。

最佳答案

你可以但不能像 sed
样本输入

akshay@db-3325:/tmp$ seq 1 5 > test.txt
akshay@db-3325:/tmp$ cat test.txt
1
2
3
4
5

在第 4 行使用 sed 输出
akshay@db-3325:/tmp$ sed '4i \ NewPage,' test.txt 
1
2
3
NewPage,
4
5

PHP 脚本
akshay@db-3325:/tmp$ cat test.php 
<?php
$new_contents = " NewPage,";
$file = "test.txt";
$line = 4;

$contents = file($file);
array_splice($contents, $line-1, 0, $new_contents.PHP_EOL);
file_put_contents($file, implode("",$contents));
?>

执行与输出
akshay@db-3325:/tmp$ php test.php 
akshay@db-3325:/tmp$ cat test.txt
1
2
3
NewPage,
4
5

否则您必须使用 exec ,但如果启用 exec 请小心在您的服务器中,人们通常会在其 php.ini 中禁用这些功能。配置
exec("sed -i '35i \ NewPage,' path/to/file 2>&1", $outputAndErrors, $return_value);
if (!$return_value) {
// Alright command executed successfully
}

Note : In general functions such as “exec” and “system” are always used to execute the external programs. Even a shell command can also be executed. If these two functions are enabled then a user can enter any command as input and execute into your server.

关于php - 如何在 PHP 中转换我的 sed 插入文本脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42007578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com