我试图从一个名为../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);
?
Run Code Online (Sandbox Code Playgroud)
我尝试过的另一个代码如下
<?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);
?>
Run Code Online (Sandbox Code Playgroud)
此代码还包括index.php文件,而不是显示它将页面显示为错误的页面.
Ja͢*_*͢ck 21
首先想到的是array_filter(),实际上是preg_grep(),但这并不重要:
$health = array_filter(glob("../health/*.php"), function($v) {
return false === strpos($v, 'index.php');
});
Run Code Online (Sandbox Code Playgroud)
随着preg_grep()使用PREG_GREP_INVERT排除模式:
$health = preg_grep('/index\.php$/', glob('../health/*.php'), PREG_GREP_INVERT);
Run Code Online (Sandbox Code Playgroud)
它避免了必须使用回调,但实际上它可能具有相同的性能
更新
适用于您的特定情况的完整代码:
$health = preg_grep('/index\.php$/', glob('../health/*.php'), PREG_GREP_INVERT);
$whathealth = $health[mt_rand(0, count($health) -1)];
include ($whathealth);
Run Code Online (Sandbox Code Playgroud)
为了称赞杰克的答案,preg_grep()您还可以:
$files = array_values( preg_grep( '/^((?!index.php).)*$/', glob("*.php") ) );
Run Code Online (Sandbox Code Playgroud)
这将返回一个数组,其中包含所有不index.php直接匹配的文件。这是您可以在index.php没有PREG_GREP_INVERT标志的情况下反转搜索的方式。
| 归档时间: |
|
| 查看次数: |
7657 次 |
| 最近记录: |