除了前20使用PHP從文本文件中的每一行除外的所有行?刪除除了前20使用PHP
回答
對於內存高效的解決方案,你可以使用
$file = new SplFileObject('/path/to/file.txt', 'a+');
$file->seek(19); // zero-based, hence 19 is line 20
$file->ftruncate($file->ftell());
+1,第一個非常優雅。 – codaddict 2010-12-10 15:29:30
道歉,錯讀的問題...
$filename = "blah.txt";
$lines = file($filename);
$data = "";
for ($i = 0; $i < 20; $i++) {
$data .= $lines[$i] . PHP_EOL;
}
file_put_contents($filename, $data);
我想這會給你一個文件,但是*前20行。如果我理解正確,@Ahsan只需要*第一個20. – 2010-12-10 15:05:40
我的不好,代碼修改! – fire 2010-12-10 15:08:18
這看起來更好,但是你最好讓那個$ i <20,否則你會閱讀21行:)你有正確的想法。 – 2010-12-10 15:08:58
如果加載在內存中的整個文件是可行的,你可以這樣做:
// read the file in an array.
$file = file($filename);
// slice first 20 elements.
$file = array_slice($file,0,20);
// write back to file after joining.
file_put_contents($filename,implode("",$file));
一個更好的解決辦法是使用功能ftruncate其中文件句柄和文件的新大小以字節爲單位,如下所示:
// open the file in read-write mode.
$handle = fopen($filename, 'r+');
if(!$handle) {
// die here.
}
// new length of the file.
$length = 0;
// line count.
$count = 0;
// read line by line.
while (($buffer = fgets($handle)) !== false) {
// increment line count.
++$count;
// if count exceeds limit..break.
if($count > 20) {
break;
}
// add the current line length to final length.
$length += strlen($buffer);
}
// truncate the file to new file length.
ftruncate($handle, $length);
// close the file.
fclose($handle);
喜歡的東西:
$lines_array = file("yourFile.txt");
$new_output = "";
for ($i=0; $i<20; $i++){
$new_output .= $lines_array[$i];
}
file_put_contents("yourFile.txt", $new_output);
使用file()將內容讀入數組,以便不必手動分解()數據。 – 2010-12-10 15:07:15
謝謝,我會更新我的答案。 – 2010-12-10 15:28:05
這應該工作以及沒有巨大的內存使用
$result = '';
$file = fopen('/path/to/file.txt', 'r');
for ($i = 0; $i < 20; $i++)
{
$result .= fgets($file);
}
fclose($file);
file_put_contents('/path/to/file.txt', $result);
- 1. 如何刪除%20%20%20 URL傳遞之前在asp.net
- 2. 使用jquery從URL中刪除%20
- 3. jQuery的刪除選項除了當前
- 4. PHP前刪除所有字符,除了最後一個號碼
- 5. 刪除除前20位的所有舊行
- 6. 刪除使用PHP
- 7. 從PHP頭重定向使用查詢字符串刪除%20
- 8. SQL:刪除,除了
- 9. 如何從用戶刪除確認刪除查詢之前使用php
- 10. 刪除和使用PHP
- 11. 如何刪除使用PHP
- 12. 使用PHP刪除文件
- 13. 刪除了TortoiseSVN
- 14. 刪除所有行除了
- 15. 使用jQuery刪除div後20使用jQuery
- 16. 使用PHP刪除錨標籤(目前使用strip_tags)
- 17. php刪除除了最後在論壇中引用的回覆
- 18. 使用REST API刪除訂單時刪除「WOO_」前綴
- 19. 刪除緩衝區前後的20個空格C
- 20. 從ImageView刪除/刪除當前圖像?
- 21. curl在php中刪除了url
- 22. 從mysql的20排起刪除
- 23. 從URL參數中刪除%20
- 24. 刪除postgis爲了使用pg_upgrade
- 25. 試圖刪除爲了使用topicmodels
- 26. NetServiceBrowser給刪除了
- 27. 如何使用php刪除/刪除mySQL中的特定錶行?
- 28. 刪除當前用戶
- 29. 使用number_with_precision刪除前導零
- 30. 如何使用AutoHotkey刪除當前行?
你應該做一些自己的研究以及。本網站補充其他資源,而不是其他互聯網的替代品。人們會很樂意提供幫助,但是,您還必須採取一些措施來幫助自己。 – DMin 2010-12-10 15:03:12