Apr 19 at 10:03am, Don Myers wrote:
> PHP gurus. I know this can be made shorter but I can't seem to figure
> out how. This is a PHP CLI script I use to go through a directory
> listing a act upon file matching the same prefix and/or suffix if
> supplied. This is the code I use now.
First of all, I made some stylistic changes. I prefer to
"interpolate {$variables} like so" or to use sprintf().
I changed your variable name $file, as there is a built-in function file().
I couldn't say if that actually would conflict or not, because I would never
do that :) Avoiding that type of potential conflict is just a good habit.
To shorten the code, I think you could just test the prefix and suffix
without checking which of them are set. I didn't test your code, but I
imagine your code would also evaluate as you expect, were they blank or
not. Same with the regex here; however, I didn't test this code either.
Hopefully this type of optimization is what you were looking for.
- Kelly
// constant; preferred date format
define('DATE_FMT','F j, Y');
// set file prefix and suffix
$deleteprefix = "";
$deletesuffix = "";
// create regex pattern
$regexpattern = sprintf('/^%s.*%s$/',$deleteprefix,$deletesuffix);
// open folder or die!
$dir_handle = @opendir($rootpath) or
die("Unable to open {$rootpath}: not folder\n");
// loop through files in directory
while ($fname = readdir($dir_handle)) {
// remove files matching the prefix/suffix, that don't start with dot
if (preg_match($regexpattern,$fname) && substr($fname,0,1) != '.') {
$modtime = date(DATE_FMT,filemtime($rootpath.$fname));
logger(sprintf('Deleted: %s Last Modified: %s',$fname,$modtime));
unlink($rootpath.$fname); }
}
--
Kelly Hallman
// Ultrafancy
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php