14

问题

我试图从一个名为 ../health/ 的文件中显示一个随机页面。在这个文件中,有一个 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 文件,但它不显示页面,而是将页面显示为错误。

4

3 回答 3

23

首先想到的是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);
于 2012-09-05T14:54:16.913 回答
5

为了恭维杰克的回答,preg_grep()您还可以这样做:

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

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

于 2012-09-05T14:59:10.003 回答
1

我的目录文件列表是:

$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
)

为你这个代码工作我在 php 8.0 中测试排除文件 index.php

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

print_r($ee);
于 2021-04-01T12:09:17.743 回答