PHP回声文件夹名称使用glob



下面使用的代码将从GLOB_BRACE中列出的3个文件夹中的任意一个中随机取出10个文件。

,

$files = (glob('../{folder1,folder2,folder3}/*.php', GLOB_BRACE)); 

我想回显url中$thelist

下面的文件夹名称
$thelist .= '<p><a href="../'.$folder 1 or 2 or 3.'/'.$file.'">'.$title.'</a></p>';

所以当它显示在我的页面上时,它是。

<p><a href="../folder1/page-name.php">what ever</a></p>
<p><a href="../folder3/page-name.php">what ever</a></p>
<p><a href="../folder1/page-name.php">what ever</a></p>
<p><a href="../folder2/page-name.php">what ever</a></p>
<p><a href="../folder1/page-name.php">what ever</a></p>
<p><a href="../folder3/page-name.php">what ever</a></p>
<p><a href="../folder2/page-name.php">what ever</a></p>
<p><a href="../folder3/page-name.php">what ever</a></p>
<p><a href="../folder1/page-name.php">what ever</a></p>
<p><a href="../folder2/page-name.php">what ever</a></p>

代码:

<?php 
$files = (glob('../{folder1,folder2,folder3}/*.php', GLOB_BRACE)); /* change php to the file you require either html php jpg png. */
shuffle($files);
$selection = array_slice($files, 0, 11);
foreach ($selection as $file) {
    $file = basename($file);
    if ($file == 'index.php') continue;
    $title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME));
        $randomlist .= '<p><a href="../'.$folder 1 or 2 or 3.'/'.$file.'">'.$title.'</a></p>';
    }
?>
<?=$randomlist?>

glob()将返回目录和文件名。因此,如果您不将$file重新分配给basename($file),则整个字符串将保持完整的输出。在if()条件下,仍然可以检查basename()continue

foreach ($selection as $file) { 
  // Call basename() in the if condition, but don't reassign the variable $file
  if (basename($file) == 'index.php') continue;
  $title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME));
  // Using the full `$file` in the HTML output. No need for basename() or dirname().
  // Using htmlentities to encode the file path for an HTML attribute
  $randomlist .= '<p><a href="' . htmlentities($file, ENT_QUOTES) . '">'.$title.'</a></p>';
}

最新更新