note 40469 added to function.unlink

From: Date: Thu, 04 Mar 2004 15:21:45 +0000
Subject: note 40469 added to function.unlink
Groups: php.notes 
Request: Send a blank email to php-notes+get-66256@lists.php.net to get a copy of this message
Just a little correction to the Pablo Rosciani's function, There is a trap because if you have a filename like "filenamepart1.filenamepart2.ext" and that you use it like unlink_wc("mydir/", "*.ext"), it won't work besause in the script : $base = "filenamepart1" $type = "filenamepart2.ext" this problem can be avoid using strrpos instead of strpos in the two lines where i add a comment /* * @Name: unlink_wc($dir,$pattern) * @Version: 1.0 * @Description: A unlink function that support wildcards ( * and ? ) * (based on code taked from php.net manual comments) * @Author: Pablo Rosciani [ pablo@nkstudios.net ] [ http://pi.nks.com.ar ] * @Date: 15/10/03 * @param string $dir Directory to search files * @param string $pattern Pattern to find. * */ function unlink_wc($dir, $pattern){ if ($dh = opendir($dir)) { //List and put into an array all files while (false !== ($file = readdir($dh))){ if ($file != "." && $file != "..") { $files[] = $file; } } closedir($dh); if (is_array($files)){ //Split file name and extenssion if(strpos($pattern,".")) { $baseexp=substr($pattern,0,strpos($pattern,".")); $typeexp=substr($pattern,strpos($pattern,".")+1,strlen($pattern)); }else{ $baseexp=$pattern; $typeexp=""; } //Escape all regexp Characters $baseexp=preg_quote($baseexp); $typeexp=preg_quote($typeexp); // Allow ? and * $baseexp=str_replace(array("\*","\?"), array(".*","."), $baseexp); $typeexp=str_replace(array("\*","\?"), array(".*","."), $typeexp); //Search for pattern match $i=0; foreach($files as $file) { $filename=basename($file); if(strpos($filename,".")) { $base=substr($filename,0,strrpos($filename,".")); // !!! use strrpos instead of strpos $type=substr($filename,strrpos($filename,".")+1,strlen($filename)); // !!! use strrpos instead of strpos }else{ $base=$filename; $type=""; } if(preg_match("/^".$baseexp."$/i",$base) && preg_match("/^".$typeexp."$/i",$type)) { $matches[$i]=$file; $i++; } } while(list($idx,$val) = each($matches)){ if (substr($dir,-1) == "/"){ unlink($dir.$val); }else{ unlink($dir."/".$val); } } } } } ---- Manual Page -- http://www.php.net/manual/en/function.unlink.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+40469 Delete -- http://master.php.net/manage/user-notes.php?action=delete+40469&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+40469&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#66256) next »