Joshua
Joshua

Reputation: 439

Link list based on directory without file extension and hyphens in php

I am using the following script for listing the files in a particular directory as a hyperlink list.

$dir = '.';
$dh = opendir($dir);
$file_count = 0;
  while (false !== ($file = readdir($dh))) {
        $files[] = $file;
        $file_count += 1;
        echo $file;
    }
  for ($x = 0; $x < $file_count; $x += 1) {
        echo "<li><a href='$files[$x]'>$files[$x]</a></li>";
    }

Please tell us whether the following is possible

1. The file extension should not be displayed

2. I need " " instead of "-" in the file names

If possible how to incorporate it.

Update 2: Thanks for your kindly help. I followed, The files names which i have mentioned must not be displayed (like dont display index.php), How do i change the code for this?

<?php
$directory = '';
foreach (glob($directory . "*.php") as $file) {
   $parts = pathinfo($file);
   $name = preg_replace("/-/", " ", $parts['filename']);
   echo "<li><a href=\"{$file}\">{$name}</a></li>";
}
?>

Upvotes: 0

Views: 483

Answers (1)

TURTLE
TURTLE

Reputation: 3847

Try the following using glob in a loop.

$directory = 'folder/';
foreach (glob($directory . "*.*") as $file) {
   $parts = pathinfo($file);
   $name = preg_replace("/-/", "", $parts['filename']);
   echo "<a href=\"{$file}\">{$name}</a>";
}

Example with your provided code, two lines added pathinfo and a preg_replace.

$dir = '.';
$dh = opendir($dir);
$file_count = 0;
while (false !== ($file = readdir($dh))) {
    $files[] = $file;
    $file_count += 1;
    echo $file;
}
for ($x = 0; $x < $file_count; $x += 1) {
    $parts = pathinfo($files[$x]);
    $name = preg_replace("/-/", "", $parts['filename']);
    echo "<li><a href='$files[$x]'>$name</a></li>";
}

Updated: The following doesn't show the files called index.php, wtf.php, and hide.php

$directory = 'folder/';
$blacklist = array(
   'index',
   'wtf',
   'hide'
);

foreach (glob($directory . "*.php") as $file) {
   $parts = pathinfo($file);
   if (!in_array($parts['filename'], $blacklist)) {
      $name = preg_replace("/-/", "", $parts['filename']);
      echo "<li><a href=\"{$file}\">{$name}</a></li>";
   }
}

Upvotes: 1

Related Questions