brian wrote:
I have a directory that contains many images (no, not pr0n,
unfortunately) and i'm working on an admin script for adding to it. I've
got something that works alright but i'm wondering if there's a Better Way.
Each image is named like: foo_01.jpg, foo_02.jpg, bar_01.jpg, and so on.
When adding a new image it should be assigned the next number in the
series (the prefix is known). Thus, given the prefix 'bar' i do
something like:
function getNextImage($path, $prefix)
{
$pattern = "/^${prefix}_([0-9]{2})\.[a-z]{3}$/";
$filenames = glob("${path}${prefix}*");
if (is_array($filenames) && sizeof($filenames))
{
sort($filenames);
/* eg. 'foo_32.jpg'
*/
$last = basename(array_pop($filenames));
/* pull the number from the filename
*/
$count = intval(preg_replace($pattern, '$1', $last));
/* increment, format with leading zero again if necessary,
* and return it
*/
return sprintf('%02d', ++$count)
}
else
{
return '01';
}
}
Note that there almost certainly will never be more than 99 images to a
series. In any case, i don't care about there being more than one
leading zero. One is what i want.
brian
Well, I didn't want to get into the middle of this cat fight, but now
that the talks have completely gotten off topic. I will interject...
Here is a function that is a bit simpler then either of yours.
Now, if you plan to delete any images in the list, this will not work.
But if you don't expect to delete any images in the list and always want
the ($total_images + 1), then follow along.
<?php
function getNextImage($path, $prefix) {
$filelist = glob("${path}${prefix}*") or return '01';
return str_pad(((int)count($filelist)+1), 2, '0', STR_PAD_LEFT);
}
?>
This should work, I don't have a setup to test it on, but you should get
the idea...
...
now remember...
if glob fails, it will return '01'
if glob returns and empty array, it will return '01'
if glob succeeds, it will return the array length + 1 padded (if needed)
by one zero
You asked for less function calls in your function, here you go
Jim
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php