Jump to content

Strip file path


swamp

Recommended Posts

Hi there, i've got this code:

 

     
           <select name="poster" id="poster">
<?php
     foreach(glob('../../author/*.txt') as $file){ //loop through all .txt files
          $file = substr($file, 0, strrpos($file, '.')); //strip the .txt extension
          echo "<option value='{$file}'>{$file}</option>"; //print the option
     }
     ?> 
    </select> 

 

Which lists all the file names into the form drop down menu. I want to strip the file name at the moment its displaying '../../author/file_here' but I want it to just display 'file_here'

 

I'm sure this is easy enough to do, I've tried exploding the '/' but couldnt get my head round it really.

 

Any help appreciated!

 

Cheers

Link to comment
https://forums.phpfreaks.com/topic/120494-strip-file-path/
Share on other sites

There may be better methods to do this, probably regular expressions, but i'm giving you a working code with string manipulation.

 

<?php
foreach(glob('../../author/*.txt') as $file){
     $file = substr($file, strrpos($file, '/') + 1); //get the position of the last / and remove what's before it
     $file = substr($file, 0, strrpos($file, '.')); //get the position of the last dot and remove what's after it
     echo "<option value='{$file}'>{$file}</option>";
} 
?>

Link to comment
https://forums.phpfreaks.com/topic/120494-strip-file-path/#findComment-620923
Share on other sites

you could simply use explode to accomplish this

 

$file = explode(".", basename($file));

 

this will now place your entire file name (with the extension) in an array

 

so to access just the extension you would call it like this:

 

echo $file[1];

 

for the filename like this

 

echo $file[0];

Link to comment
https://forums.phpfreaks.com/topic/120494-strip-file-path/#findComment-621290
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.