7

ファイルに追加されている文字列がまだファイルにないかどうかを確認してから追加することはできますか? 今、私は使用しています

        $myFile = "myFile.txt";
    $fh = fopen($myFile, 'a') or die("can't open file");
    $stringData = $var . "\n";
    fwrite($fh, $stringData);
    fclose($fh);

しかし、私は $var 値の多くの重複を取得し、それらを取り除きたいと思っていました. ありがとうございました

4

7 に答える 7

4

これを使って

$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);
}
于 2013-03-07T11:09:23.123 に答える
1

最善の方法は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);
}
于 2013-03-07T11:09:27.627 に答える
1
$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
}
于 2013-03-07T11:09:40.257 に答える
0

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バイトを取り出すことができます) 。

于 2013-03-07T11:21:53.747 に答える
0

考えられる解決策は次のとおりです。

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.
于 2013-03-07T11:08:44.143 に答える
0
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
于 2013-03-07T11:09:03.223 に答える
0

追加したすべての文字列を配列に保存し、現在の文字列が追加されているかどうかをin_arrayで確認できます。

2 番目の選択肢は、書き込みたいたびにファイルを読み取り、strstrを実行することです。

于 2013-03-07T11:09:43.820 に答える