使用 glob 排除 index.php 的 PHP 代码 [英] PHP code to exclude index.php using glob

查看:18
本文介绍了使用 glob 排除 index.php 的 PHP 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to display a random page from a file called ../health/ In this file there is a index.php file and 118 other files named php files. I would like to randomly display a file from the health folder but i would like it to exclude the index.php file.

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

This following code includes the index.php file sometimes. I have also tried altering the $exclude line to show ../health/index.php but still no luck.

<?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);
?

我尝试过的另一个代码如下

Another code i have tried is the following

<?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 文件,但它没有显示页面,而是将页面显示为错误.

This code also includes the index.php file but rather than showing the page it displays the page as an error.

推荐答案

首先想到的是array_filter(),其实是preg_grep(),但这没关系:

The first thing that came to mind is array_filter(), actually it was preg_grep(), but that doesn't matter:

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

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

With preg_grep() using PREG_GREP_INVERT to exclude the pattern:

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

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

更新

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

The full code that should work for your particular case:

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

这篇关于使用 glob 排除 index.php 的 PHP 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆