使用glob排除index.PHP的PHP代码


PHP code to exclude index.php using glob

问题

我正在尝试显示一个名为..的文件中的随机页面/健康/在这个文件中有一个index.php文件和其他118个名为php文件的文件。我想随机显示健康文件夹中的一个文件,但我希望它排除index.php文件。

以下代码有时包括index.php文件。我还尝试更改$exclude行以显示/health/index.php,但仍然没有运气。

<?php
$exclude = array("index.php"); // can add more here later
$answer = array_diff(glob("../health/*.php"),$exclude);
$whatanswer = $answer[mt_rand(0, count($answer) -1)];
include ($whatanswer);
?

我尝试过的另一个代码是以下

<?php
$exclude = array("../health/index.php"); // can add more here later
$health = glob("../health/*.php");
foreach ($health as $key => $filename) {
foreach ($exclude as $x) {
if (strstr($filename, $x)) {
unset($whathealth[$key]);
}
}
}
$whathealth = $health[mt_rand(0, count($health) -1)];
include ($whathealth);
?>

这段代码还包括index.php文件,但它没有显示页面,而是将页面显示为错误。

首先想到的是array_filter(),实际上是preg_grep(),但这并不重要:

$health = array_filter(glob("../health/*.php"), function($v) {
    return false === strpos($v, 'index.php');
});

使用preg_grep()使用PREG_GREP_INVERT排除模式:

$health = preg_grep('/index'.php$/', glob('../health/*.php'), PREG_GREP_INVERT);

它避免了使用回调,尽管实际上它可能具有相同的性能

更新

应该适用于您的特定情况的完整代码:

$health = preg_grep('/index'.php$/', glob('../health/*.php'), PREG_GREP_INVERT);
$whathealth = $health[mt_rand(0, count($health) -1)];
include ($whathealth);

为了称赞Jack的回答,使用preg_grep()还可以执行以下操作:

$files = array_values( preg_grep( '/^((?!index.php).)*$/', glob("*.php") ) );

这将直接返回一个数组,其中包含与index.php不匹配的所有文件。这就是在没有PREG_GREP_INVERT标志的情况下反转搜索index.php的方法。

我的目录文件列表是:

$ee = glob(__DIR__.DIRECTORY_SEPARATOR.'*',GLOB_BRACE);

结果

Array
(
    [0] => E:'php prj'goroh bot'bot.php
    [1] => E:'php prj'goroh bot'index.php
    [2] => E:'php prj'goroh bot'indexOld.php
    [3] => E:'php prj'goroh bot'test.php
)

我将代码写入test.php并运行它

只需像这样使用glob:

$ee = glob(__DIR__.DIRECTORY_SEPARATOR.'[!{index}]*',GLOB_BRACE);
print_r($ee);

将其用于排除文件和目录名称以索引开头

结果

(
    [0] => E:'php prj'goroh bot'bot.php
    [1] => E:'php prj'goroh bot'test.php
)

这对于排除文件名以结尾

$ee = glob(__DIR__.DIRECTORY_SEPARATOR.'*[!{Old}].*',GLOB_BRACE);
print_r($ee);

结果

Array
(
    [0] => E:'php prj'goroh bot'bot.php
    [1] => E:'php prj'goroh bot'index.php
    [2] => E:'php prj'goroh bot'test.php
)

对于您的代码工作,我在php8.0中测试excludefilesindex.php

$ee = glob(__DIR__.DIRECTORY_SEPARATOR.'*[!{index}].php',GLOB_BRACE);
print_r($ee);