Search code examples
phpgalleryjssor

How to remove beginning of filename in PHP?


I'm making a gallery in jssor and the slides are made by reading a directory and writing the div for every image using a PHP script. Under the image a caption is displayed with the name of the artist (this is always the same) followed by the file name without the extension.

This is what I have so far:

<?

$dir = 'Photo/Paintings';
$files = scandir($dir);
sort($files);
foreach ($files as $file) {
    if ($file != '.' && $file != '..') {
        echo '<div>
                <img u="image" style="max-height:460px;" src="Photo/Paintings/'.$file.'" />
               <img u="thumb" src="Photo/Paintings/'.$file.'" />';
        $withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $file);
            echo '<div u="caption" style="position: absolute; top: 470px; left: 0px; height: 10px; text-align: center;">
                      ARTISTX - '.$withoutExt.'
              </div>
        </div>';
    }
}

?> 

These images should be in a particular order, so my idea was to add a number at the beginning of every filename like so #5-Picture of tree.jpg. My question is, how do I remove this #5 part from being displayed in the caption as well?

Alternatively, is there a better way to determine the order of these files? I realize now my idea wouldn't even work very well since #1 would alphabetically be followed by #11 and #12 instead of #2. I could maybe work around this by using a combination with letters 1A, 1B, 1C, 2A, etc.


Solution

  • This only take effect if the file name actually starts with a number:

    $str = preg_replace('/^\\d+-/', null, $fileName);
    

    Files which do not start with #{number}- will not be affected by this tailoring process.

    For your sorting problem. Put a filling 0 before. So use 01, 02, ... and so on up to 99.

    By the way. Don't use short PHP tags. Always use <?php at the beginning of a PHP block.