![](/img/trans.png)
[英]How do I insert values from a form using php and sql using my own script?
[英]How do I convert my sed insert text script in PHP?
我有一個可以工作的 sed 腳本,可以在行號處將文本插入到文檔中。
sed -i '35i \ NewPage,' file
想知道是否有辦法使用 php 獲得相同的結果。 35 i 是要插入的行號 \\ 換行插入 NewPage 是要插入的文本 file 是文件位置
有什么建議? 最好的問候 AT。
你可以但不能像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
}
注意:一般來說,諸如“exec”和“system”之類的函數總是用於執行外部程序。 甚至shell命令也可以執行。 如果啟用了這兩個功能,則用戶可以輸入任何命令作為輸入並在您的服務器中執行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.