1

ファイルの先頭から最初の 23 行を削除し、10 行を含む文字列に置き換えたいとします。

$newstring = "line1
2
3
4
5
6
7
8
9
10";

それについて行く最も簡単な方法は何ですか?で遊んでいますがfwrite、間違いなく何か間違っています。

4

1 に答える 1

1
replace_first_lines_in_file('path/to/file.txt', 23, $new_string);


function replace_first_lines_in_file( $file_path, $num_lines, $new_string )
{

    $file = file_get_contents($file_path);
    if( ! $file )
        return false;

    $pattern = '#^([^\n]*\n){' . $num_lines . '}#si';
    $new_file = preg_replace($pattern, $newstring, $file);

    if( ! file_put_contents($file_path, $new_file) )
        return false;

    return true;

}
于 2012-08-11T15:16:36.150 に答える