如何检查txt文件中是否已存在值

如何检查txt文件中是否已存在值

问题描述:

I am writing UserID's to a text file seperated with || The var $UserID is an integer like 1, 2, 3 etc.

If a user has ID 1; the value is stored in the txt file and looks after some time like this:

1||1||1||1||1||...

What i want to achieve: if an ID is already stored in the txt file, do not store it again.

this is what i have sofar;

$UserIdtxt = $UserID."||";


$ID = explode("||", file_get_contents("user_id.txt"));
  foreach($ID as $IDS) {

// here must come the check if the ID already is stored in the txt file
     if($IDS != $UserID) {
     file_put_contents("user_id.txt", $UserIdtxt, FILE_APPEND);

     }
  }

How can i make that check?

我正在将UserID写入一个用 || code>分隔的文本文件 var $ UserID code>是一个整数,如1,2,3等。 p>

如果用户的ID为1; 该值存储在txt文件中,并在一段时间后查看: p>

1 || 1 || 1 || 1 || 1 || ... code> p>

我想要实现的目标: 如果ID已经存储在txt文件中,请不要再存储它。 p>

this 是我的软件; p>

  $ UserIdtxt = $ UserID。“||”; 
 
 
 $ ID = explode(“||”,file_get_contents(“  user_id.txt“)); 
 foreach($ ID as $ IDS){
 
 //这里必须检查ID是否已存储在txt文件中
 if($ IDS!= $ UserID)  {
 file_put_contents(“user_id.txt”,$ UserIdtxt,FILE_APPEND); 
 
} 
} 
  code>  pre> 
 
 

如何进行检查? div>

All you need to do is test if the new ID is aleady in the exploded array using in_array()

$UserIdtxt = $UserID."||";

$all_ids = explode("||", file_get_contents("user_id.txt"));

if ( ! in_array($UserID, $all_ids) ) {
    file_put_contents("user_id.txt", $UserIdtxt, FILE_APPEND);
}

But this is an awful way of storing this kind of information

Prob a good idea to make sure the file was read successfully before you scan it

if($source = file_get_contents("user_id.txt"){
    if(!preg_match("/^($UserID|.*\|\|$UserID)/", $source){
        ... //add id to file
    }
}else{/*Todo: handle file-open failure*/}