【问题标题】:Insert lines in a file (YML) from specific line从特定行在文件 (YML) 中插入行
【发布时间】:2012-11-30 16:59:34
【问题描述】:

我想使用 PHP 在文件中插入行,但从文件中的特定行开始。

我的文件 acme.yml 有一行 shortcuts:。我想在它前面插入几行。

#newlines here
shortcuts:

我在PHP手册中看到了file_get_contentsfile_put_contents这两个函数,但不知道是不是最好的办法。

<?php
    $file = 'acme.yml';
    $newlines = array($line1, $line2, $line3);

    $current = file_get_contents($file);

    #TODO:

    file_put_contents($file, $current);
?>

也许在 yml 文件中有更好的方法。

【问题讨论】:

    标签: php yaml


    【解决方案1】:
    <?php
    
    $file = 'acme.yml';
    $newlines = array($line1, $line2, $line3);
    
    $current = file_get_contents($file);
    
    $current = str_replace("shortcuts:\n", implode("\n", $newlines) . "\nshortcuts:\n", $current);
    
    file_put_contents($file, $current);
    
    ?>
    

    试试这个。

    【讨论】:

      猜你喜欢
      • 2012-10-30
      • 1970-01-01
      • 2013-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多