简体   繁体   中英

replace string with string+new line in file

Ongoing Series
Series 2
Series 1

I want to insert series 3 between first and second line with replacing series 2 with series 3 \\n series 2 using file_get_contents file_put_contents with out success

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM