2013-03-07 73 views
6

是否可以檢查被添加到文件的字符串是否已經在文件中,然後才添加它?現在我正在使用如果字符串是唯一的,Php追加到文件

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

但是我得到很多$ var值的重複,並且想擺脫它們。 謝謝

+0

你能否更加澄清$ var – Ranjit 2013-03-07 11:09:40

+0

更多的信息會使這個問題更容易回答。該文件是否總是以換行符分隔?這個字符串是固定長度的嗎?文件很小(* file_get_contents * *可行)還是龐大? – Dan 2013-03-07 11:23:58

回答

3

使用本

$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); 
} 
+1

+1幾乎相同的時間:) – Rikesh 2013-03-07 11:10:22

+1

如果字符串發現在0位置0 – 2013-03-07 11:10:39

+0

@Akam,它可以用strpos()=== FALSE' – fedorqui 2013-03-07 11:16:14

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. 
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 
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); 
} 
+1

'if(!strpos(「some text」,「some」)){echo「not found」; }'檢查一下! – 2013-03-07 11:14:30

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 
} 
0

,你可以保存在陣列中的所有讓您的字符串,並與in_array的檢查,如果當前字符串已添加或不。

第二種選擇是每次要寫入read the file並在其上執行strstr

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 

這個答案僅僅是基於這樣的事實,你已經附加在你的代碼,這就是爲什麼fgets將在這裏工作換行符("\n")。這可能比用file_get_contents()將整個文件拖入內存更好,只是因爲文件的大小可能會阻止這種情況發生。

備選地,如果值不換行分隔,但固定長度,則可以始終使用的fgets()$length參數拉恰好$n字符出來(或使用fread()拉恰好$n字節出