0

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

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
dhornbein
  • 214
  • 8
  • 19

5 Answers5

4

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

str_replace('_', ' ', basename($path, ".jpg"));
rpjohnst
  • 1,612
  • 14
  • 21
1
  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()

Srikar Doddi
  • 15,499
  • 15
  • 65
  • 106
0
$actual_name = str_replace('_', ' ', basename($input));
Lucky
  • 646
  • 4
  • 9
0

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
  • 395,085
  • 80
  • 655
  • 663
0

Path info and str_replace.

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