2012-11-30 16 views
1

我想使用PHP將行插入到文件中,但是從文件中的特定行中插入。從特定行中的文件(YML)中插入行

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

#newlines here 
shortcuts: 

我看到的功能file_get_contentsfile_put_contents PHP手冊中,但我不知道這是否是最好的辦法。

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

    $current = file_get_contents($file); 

    #TODO: 

    file_put_contents($file, $current); 
?> 

也許有更好的方式來做到這一點在YML文件。

回答

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); 

?> 

試試這個。