使用 glob 的 php echo 文件夹名称

标签 php arrays echo shuffle glob

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

例如:

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

我想在 $thelist 下面看到的 url 中回显文件夹名称

$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()继续

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>';
}

关于使用 glob 的 php echo 文件夹名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14429922/

相关文章:

php - GET方法和PHP

php - 创建一个 php 文件以动态翻译内容

javascript - 数组对象数组问题

javascript - 数组的拼接是否会减少 array.length 的值?

javascript - 我如何创建自己的 url,如 ws ://echo. websocket.org?

PHP 向 STDERR 写入大量文本

php - 从表单中捕获用户输入

php - 在 sentora 网站面板 w.r.t Cpanel [控制面板] 中设置 crons

php - 根据特定键在对象数组中查找重复项

php - 在 IMG 标签中回显图像路径