用字符串替换字符串+文件中的新行

时间:2016-05-30 10:12:17

标签: php string file newline

Ongoing Series
Series 2
Series 1

我想在第一行和第二行之间插入系列3,并使用file_get_contents file_put_contents替换系列3 \ n系列2,而不是成功

2 个答案:

答案 0 :(得分:0)

$text = file_get_contents("myfile.txt")
$text = preg_replace('/Series 2\s+/si', 'Series 2\nSeries 3\n', $text);
file_put_contents("newfile.txt", $text);

答案 1 :(得分:0)

$flename = "filename";
$newString = "series 3"; 

// Read file to array
$lines = file($filename);
// Add line after the fist one 
array_splice($lines, 1, 0, $newString . PHP_EOL);
// Write back
file_put_contents($filename, implode('', $lines)); 
相关问题