【问题标题】:How do I convert my sed insert text script in PHP?如何在 PHP 中转换我的 sed 插入文本脚本?
【发布时间】:2017-06-19 20:10:56
【问题描述】:

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

sed -i '35i \ NewPage,' file

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

有什么建议吗? 最好的祝福 AT。

【问题讨论】:

    标签: php ubuntu nginx replace sed


    【解决方案1】:

    你可以但不能像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命令也可以 被执行。如果启用这两个功能,则用户可以输入 任何命令作为输入并在您的服务器中执行。

    【讨论】:

      猜你喜欢
      • 2021-09-29
      • 1970-01-01
      • 2017-06-15
      • 1970-01-01
      • 2013-04-30
      • 2012-07-09
      • 1970-01-01
      • 2018-11-09
      相关资源
      最近更新 更多