tags:

views:

378

answers:

5

I have an array of image files with relative paths, like this: gallery/painting/some_image_name.jpg. I am passing this array into a foreach loop which prints the path into the source of an <img>.

What is a safe reliable way to pull the name from a line such as that?

gallery/painting/some_image_name.jpg > to > some image name

+4  A: 

basename($path, ".jpg") gives some_image_name, then you could replace _ with space.

str_replace('_', ' ', basename($path, ".jpg"));
Rusky
A: 

$actual_name = str_replace('_', ' ', basename($input));

Lucky
A: 

Hi,

What about using pathinfo to extract the parts that compose the file's name ?

For instance :

$name = 'gallery/painting/some_image_name.jpg';
$parts = pathinfo($name);
var_dump($parts);

Which will get you :

array
  'dirname' => string 'gallery/painting' (length=16)
  'basename' => string 'some_image_name.jpg' (length=19)
  'extension' => string 'jpg' (length=3)
  'filename' => string 'some_image_name' (length=15)

And then, you can use str_replace to replace the _ by spaces :

$name2 = str_replace('_', ' ', $parts['filename']);
var_dump($name2);

And you'll get :

string 'some image name' (length=15)
Pascal MARTIN
+1  A: 
  function ShowFileName($filepath) 
    { 
        preg_match('/[^?]*/', $filepath, $matches); 
        $string = $matches[0]; 
        #split the string by the literal dot in the filename 
        $pattern = preg_split('/\./', $string, -1, PREG_SPLIT_OFFSET_CAPTURE); 
        #get the last dot position 
        $lastdot = $pattern[count($pattern)-1][1]; 
        #now extract the filename using the basename function 
        $filename = basename(substr($string, 0, $lastdot-1)); 
        #return the filename part 
        return $filename; 
    }

Reference: http://us2.php.net/basename()

CodeToGlory
This seems like a bit of over kill compared to Rusky's code. What is the benefit to this method?
DrGlass
A: 

Path info and str_replace.

     $path = 'gallery/painting/some_image_name.jpg';
     $r = pathinfo($path, PATHINFO_FILENAME);
     echo str_replace('_', ' '. $r['filename']);
scragar