TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   General (http://www.talkphp.com/general/)
-   -   Splitting Filenames (http://www.talkphp.com/general/4566-splitting-filenames.html)

rguy84 06-17-2009 08:51 AM

Splitting Filenames
 
I have a directory that will hold word docs of meeting minutes. The word doc titles will be "Minutes 1-21-2009.doc". I would basically I want the names to be "Minutes - 1-21-2009". Right now my code looks like:
PHP Code:

$min_dir blah;
if(
is_dir($min_dir)){
if(
$min opendir($min_dir)){
while((
$file readdir($min)) !== false){
if (
$file != "." && $file != "..") {
list(
$fliemin,$fileextra) = explode(' ',$file);
list(
$filedate,$fileext) = explode('.',$fileextra);
"<li><a href=\"minutes/$file\">Minutes - $filedate</a></li>";
}
}
closedir($min);
}


This works fine, I just wanted to see if there was a cleaner way to make this a bit cleaner (the part in the inner most if())

Salathe 06-17-2009 10:48 AM

It's a totally different approach to your script, but I think the following is much cleaner.

PHP Code:

$path  'path/to/files';
$files glob($path.'/Minutes *.doc');
foreach (
$files as $file)
{
    
// Minutes 1-2-2003.doc
    
$basename basename($file);
    
// Minutes 1-2-2003
    
$no_ext   basename($basename'.doc');
    
// 1-2-2003
    
$date     substr($no_ext8);
    
printf('<li><a href="minutes/%s">Minutes - %s</a></li>'$basename$date);



rguy84 06-17-2009 05:53 PM

...wow that is much cleaner. A few questions. I see you defined the extension explicitly, is there a way to catch if it is .docx? If the person upgrades.

Salathe 06-17-2009 06:04 PM

For the glob, look into GLOB_BRACE (on the glob manual page if you want to look for multiple discrete possibilities (such as .doc and .docx). For the $no_ext line, you could call pathinfo($basename, PATHINFO_FILENAME) which will cut off the extension whatever it is.

rguy84 06-17-2009 06:22 PM

I just looked, and you can use multiple astricks, so can't you just logically do:
PHP Code:

$files glob($path.'/Minutes *.doc*'); 
//or
$files glob($path.'/Minutes *'); 


Salathe 06-17-2009 11:40 PM

Sure, if you know the files in there will only ever be of a certain pattern which those match (for example, no ".doc.bak" files).

rguy84 06-18-2009 06:13 AM

.doc.bak would be covered by the *.doc*. However it wouldn't be happy with stripping the ext.


All times are GMT. The time now is 04:59 AM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0