파일의 처음부터 처음 23 줄을 제거하고 10 줄을 포함하는 문자열로 바꾸고 싶습니다.첫 번째 23 줄을 10 줄짜리 문자열로 대체하십시오.
$newstring = "line1
2
3
4
5
6
7
8
9
10";
가장 쉬운 방법은 무엇입니까? 나는 fwrite
으로 놀고 있었지만 분명히 뭔가 잘못하고 있습니다.
파일의 처음부터 처음 23 줄을 제거하고 10 줄을 포함하는 문자열로 바꾸고 싶습니다.첫 번째 23 줄을 10 줄짜리 문자열로 대체하십시오.
$newstring = "line1
2
3
4
5
6
7
8
9
10";
가장 쉬운 방법은 무엇입니까? 나는 fwrite
으로 놀고 있었지만 분명히 뭔가 잘못하고 있습니다.
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;
}
감사합니다. 그러나 나는 읽고있는 파일과 동일한 파일에 쓰고 싶습니다. 읽고있는 파일에 file_put_contents를 사용할 수 있습니까? – John
예. 당신은 그것으로부터 읽습니다. 그런 다음 2 개의 개별 작업입니다. 당신은 동시에 읽고 쓰는 것이 아닙니다. – HappyTimeGopher
@ 존 귀하의 의견에 따라 편집 됨. – HappyTimeGopher
[당신이 시도 무엇?] (http://whathaveyoutried.com) – Don
http://stackoverflow.com/questions/215896/how-to-use-php-to-delete-x-number -of-lines-from-the-text-file – Stony
마지막으로 시도한 것은 preg_replace로 빈 줄을 제거한 다음 10 줄의 텍스트와 13 줄의 빈 줄을 $ txtw = fopen ('txt .txt ','r '); fwrite ($ txtw, $ newstring); fclose ($ txtw); – John