我相信fgets就是這裏的答案。
$handle = fopen($path, 'r+'); // open the file for r/w
while (!feof($handle)) { // while not end
$value = trim(fgets($handle)); // get the trimmed line
if ($value == $input) { // is it the value?
return; // if so, bail out
} //
} // otherwise continue
fwrite($handle, $input); // hasn't bailed, good to write
fclose($handle); // close the file
這個答案僅僅是基於這樣的事實,你已經附加在你的代碼,這就是爲什麼fgets
將在這裏工作換行符("\n"
)。這可能比用file_get_contents()
將整個文件拖入內存更好,只是因爲文件的大小可能會阻止這種情況發生。
備選地,如果值不換行分隔,但固定長度,則可以始終使用的fgets()
的$length
參數拉恰好$n
字符出來(或使用fread()
拉恰好$n
字節出)
來源
2013-03-07 11:21:53
Dan
你能否更加澄清$ var – Ranjit 2013-03-07 11:09:40
更多的信息會使這個問題更容易回答。該文件是否總是以換行符分隔?這個字符串是固定長度的嗎?文件很小(* file_get_contents * *可行)還是龐大? – Dan 2013-03-07 11:23:58