Jake Gosling
Jake Gosling

Reputation: 3

remove extension from image filename php

I am loading a folder of images into a html page using the following php code.

The problem I am having is that the file name which is being brought through in order to be used as the image caption is showing the file extension.

The part of the code where the name is being pulled is the title='$img'

How do I get it to remove the file extension?

<?php
$string =array();
$filePath='images/schools/';  
$dir = opendir($filePath);
while ($file = readdir($dir)) { 
    if (eregi("\.png",$file) || eregi("\.jpeg",$file) || eregi("\.gif",$file) || eregi("\.jpg",$file) ) { 
        $string[] = $file;
    }
}
while (sizeof($string) != 0) {
    $img = array_pop($string);
    echo "<img src='$filePath$img' title='$img' />";
}

?>

Upvotes: 0

Views: 3285

Answers (4)

Vinh
Vinh

Reputation: 1

you can get rid of file extention with substr, like this:

$fileName =  $request->file->getClientOriginalName();
$file_without_ext = substr($fileName, 0, strrpos($fileName,"."));

Upvotes: -1

Shi
Shi

Reputation: 4258

For a "state-of-the-art" OO code, I suggest the following:

$files = array();
foreach (new FilesystemIterator('images/schools/') as $file) {
    switch (strtolower($file->getExtension())) {
        case 'gif':
        case 'jpg':
        case 'jpeg':
        case 'png':
            $files[] = $file;
            break;
    }
}

foreach ($files as $file) {
    echo '<img src="' . htmlentities($file->getPathname()) . '" ' .
         'title="' . htmlentities($file->getBasename('.' . $file->getExtension())) . '" />';
}

Benefits:

  • You do not use the deprecated ereg() functions anymore.
  • You escape possible special HTML characters using htmlentities().

Upvotes: 0

Poe
Poe

Reputation: 3010

You can get the filename without the extension using pathinfo so for title='' you could use pathinfo($file, PATHINFO_FILENAME);

Upvotes: 3

Peter
Peter

Reputation: 16933

$file_without_ext = substr($file, 0, strrpos(".", $file));

Upvotes: 1

Related Questions