I just discovered glob as a faster way to perform a task I need done. I want to read a subdirectory and create links with the output. Here is the code and the questions follow. <?php //Take all file names in the directory and put them in a link. foreach (glob("dir_name/*.*") as $filename) { echo "<a href=\"".$filename."\">".$filename."</a><br/>"; } ?> Code (markup): This works fine except the output to the browser reads as dir_name/filename.ext. What I want to do is maintain the link exactly as it is and strip the dir_name and .ext (dot extension) from the browser display. I fell like I need to use explode but am not sure exactly to write the code to do that.
Have a look at pathinfo... http://www.php.net/manual/en/function.pathinfo.php It will split your filename up into the path, the extension, the filename etc...
foreach (glob("dir_name/*.*") as $filename) { echo '<a href="' . $filename. '">' . array_pop(explode('/', array_shift(explode('.', $filename)))) . '</a><br/>'; } PHP: There you go, although strictly speaking, you shouldn't have a function inside a function, let alone 3 functions inside 1. But as you're attempting to do it all in 1 line, I'm sure you'll appreciate it more this way.
For PHP 5.2.0+ pathfinfo($filename, PATHINFO_FILENAME) PHP: Or: basename($filename, '.' . end(explode('.', $filename))) PHP: Umm... before I rant about it, I'd rather hear your reason for this.
His posted solution worked fine. I don't know enough to comment on his statement. I can say that the execution slowed down based on the straight glob. Just enough to notice. Most people would not.
I have no personal reasons as to why not aside from readability, but if you put PHP in its pedantic mode it will throw you a notification. Reps...?