我相信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