Search code examples
phpglob

Using glob to filename parameters


Here's what I need, I have files: "page-Home1.php", "page-Contact2.php". Yes I understand they don't have beautiful names but that's not what I'm worrying about right now, what I need is for glob to echo the files in order by 1,2,3 etc..

I currently have:

<?php
foreach (glob("page-*") as $filename) {
    $result = str_replace("page-","", $filename);
    $result = str_replace(".php","", $result);
    echo "<li><a href='" . $filename ."'/>". $result . "</a></li><tr>";
}
?>

Though that only spits them out in a random order, I need it to number order.... Any ideas?


Solution

  • $files = glob(dirname(__FILE__).'/page-*.php');
    
    foreach ($files as $file) {
        $result[preg_replace('#[^0-9]#','', $file)]['file'] = $file;
        $result[preg_replace('#[^0-9]#','', $file)]['name'] = str_replace(array("page-", ".php"), array('', ''), $file);;
    }
    
    sort($result);
    
    foreach($result as $data) {
        echo $data['file'].' -> '.$data['name'].'<br>';
    }