title: How to use php keep only specific file and remove others in directory?
body: <p>How to use php keep only specific file and remove others in directory?  </p>
  
  <p>example:<br>
  <code>1/1.png, 1/2.jpeg, 1/5.png ...</code></p>
  
  <p>the file number, and file type is random like x.png or x.jpeg, but I have a string <code>2.jpeg</code> the file need to keep.</p>
  
  <p>any suggestion how to do this??</p>
  
  <p>Thanks for reply, now I coding like below but the unlink function seems not work delete anything.. do I need change some setting?  I'm using Mamp </p>
  
  <p>UPDATE  </p>
  
  <pre><code>// explode string &lt;img src="u_img_p/5/x.png"&gt;
  $content_p_img_arr = explode('u_img_p/', $content_p_img);
  $content_p_img_arr_1 = explode('"', $content_p_img_arr[1]);    // get 5/2.png"&gt;
  $content_p_img_arr_2 = explode('/', $content_p_img_arr_1[0]);    // get 5/2.png
  print $content_p_img_arr_2[1];    // get 2.png   &lt; the file need to keep
  
  $dir = "u_img_p/".$id;  
  if ($opendir = opendir($dir)){
      print $dir;
      while(($file = readdir($opendir))!= FALSE )
          if($file!="." &amp;&amp; $file!= ".." &amp;&amp; $file!= $content_p_img_arr_2[1]){
              unlink($file);
              print "unlink";
              print $file;
          }
      }
  } 
  </code></pre>
  
  <p>I change the code unlink path to folder, then it works!!</p>
  
  <pre><code> unlink("u_img_p/".$id.'/'.$file);  
  </code></pre>