【问题标题】:replace string with string+new line in file用文件中的字符串+新行替换字符串
【发布时间】:2016-05-30 10:12:17
【问题描述】:
Ongoing Series
Series 2
Series 1

我想在第一行和第二行之间插入系列 3,并使用 file_get_contents file_put_contents 将系列 2 替换为系列 3 \n 系列 2,但没有成功

【问题讨论】:

    标签: php string file newline


    【解决方案1】:
    $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)); 
    

    【讨论】:

    • 很高兴为您提供帮助。祝你好运!
    【解决方案2】:
    $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);
    

    【讨论】:

    • 没有工作输出是(系列 2\n 系列 3\n)但是thanx :)
    猜你喜欢
    • 2017-09-04
    • 2018-01-14
    • 2019-01-11
    • 1970-01-01
    • 2015-10-14
    • 1970-01-01
    • 2011-07-01
    • 2015-07-31
    • 1970-01-01
    相关资源
    最近更新 更多