Reputation: 1034
I've got this code:
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'html')
{
$patterns = array();
$patterns[0] = '/_/';
$patterns[1] = '/.html/';
$patterns[2] = '/index/';
$replacements = array();
$replacements[2] = ' ';
$replacements[1] = '';
$replacements[0] = 'Strona główna';
$wynik = preg_replace($patterns, $replacements, $file);
$newVariable = str_replace("_", " ", $file);
$thelist .= '<li><a href="'.$file.'">'.ucfirst($wynik).'</a></li>';
}
}
closedir($handle);
}
?>
<P>List of files:</p>
<P><?=$thelist?></p>
Is there a way to display the list of files in alphabetic order? Now the script lists html files in the directory where it is. How to modify the script that I can manualy set the directory to read?
//Code with alphabetical order:
<?php
if ($handle = opendir('.')) {
$files = glob("*");
foreach ($files as $file) // replace `while` with `foreach`
{
if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'html')
{
$patterns = array();
$patterns[0] = '/_/';
$patterns[1] = '/.html/';
$patterns[2] = '/index/';
$replacements = array();
$replacements[2] = ' ';
$replacements[1] = '';
$replacements[0] = 'Strona główna';
$wynik = preg_replace($patterns, $replacements, $file);
$newVariable = str_replace("_", " ", $file);
$thelist .= '<li><a href="'.$file.'" target="_blank">'.ucfirst($wynik).'</a></li>';
}
}
closedir($handle);
}
?>
Upvotes: 1
Views: 919
Reputation: 95101
You can use SplHeap
foreach(new AlphabeticDir(__DIR__) as $file)
{
//Play Some Ball
echo $file->getPathName(),PHP_EOL;
}
Class
class AlphabeticDir extends SplHeap
{
public function __construct($path)
{
$files = new FilesystemIterator($path, FilesystemIterator::SKIP_DOTS);
foreach ($files as $file) {
$this->insert($file);
}
}
public function compare($b,$a)
{
return strcmp($a->getRealpath(), $b->getRealpath());
}
}
Upvotes: 0
Reputation: 3558
I'd add the file information to an array, sort the array, then echo out the information using a loop including your formatting.
Upvotes: 1