是否可以检查正在添加到文件的字符串是否不在文件中,然后才添加它?现在我正在使用
        $myFile = "myFile.txt";
    $fh = fopen($myFile, 'a') or die("can't open file");
    $stringData = $var . "\n";
    fwrite($fh, $stringData);
    fclose($fh);
但是我得到了许多重复的 $var 值,并想摆脱它们。谢谢
用这个
$file = file_get_contents("myFile.txt");
if(strpos($file, $var) === false) {
   echo "String not found!";
   $myFile = "myFile.txt";
   $fh = fopen($myFile, 'a') or die("can't open file");
   $stringData = $var . "\n";
   fwrite($fh, $stringData);
   fclose($fh);
}
最好的方法是file_get_contents仅当 $var 不在您的文件中时才使用和执行操作。
$myFile = "myFile.txt";
$file = file_get_contents($myFile);
if(strpos($file, $var) === FALSE) 
{
   $fh = fopen($myFile, 'a') or die("can't open file");
   $stringData = $var . "\n";
   fwrite($fh, $stringData);
   fclose($fh);
}
$myFile = "myFile.txt";
$filecontent = file_get_contents($myFile);
if(strpos($filecontent, $var) === false){
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = $var . "\n";
fwrite($fh, $stringData);
fclose($fh);
}else{
 //string found
}
可能的解决方案可能是:
1. Fetch the contents using fread or file_get_contents
2. Compare the contents with the current contents in file
3. add it if it is not there.
function find_value($input) {
  $handle = @fopen("list.txt", "r");
   if ($handle) {
    while (!feof($handle)) {
     $entry_array = explode(":",fgets($handle));
     if ($entry_array[0] == $input) {
      return $entry_array[1];
     }
  }
 fclose($handle);
}
return NULL;
}
你也可以这样做
$content = file_get_contents("titel.txt");
$newvalue = "word-searching";
//Then use strpos to find the text exist or not
我相信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
这个答案完全基于您"\n"在代码中添加了换行符 ( ) 的事实,这就是为什么fgets会在这里工作。这可能比使用 将整个文件拉入内存更可取file_get_contents(),因为文件的大小可能会让人望而却步。
或者,如果值不是换行符分隔,而是固定长度,您始终可以使用$length参数fgets()来精确提取$n字符(或使用fread()精确提取$n字节)