PHP code,以排除使用index.php的水珠 [英] PHP code to exclude index.php using glob
问题描述
我想显示来自一个名为../health/文件随机页面
在这个文件中有一个index.php文件,并命名为118 PHP文件的其他文件。
我想随机显示从卫生文件夹中的文件,但我想它排除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.
这下code包含index.php文件的时候。
我也试图改变$排除线来表示../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);
?
另外code我曾尝试如下
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);
?>
这code还包括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
排除模式:
$health = preg_grep('/index\.php$/', glob('../health/*.php'), PREG_GREP_INVERT);
的它避免了使用回调,虽然实际上它很可能有同样的表现的
更新
满code应为您的特定情况下工作:
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);
这篇关于PHP code,以排除使用index.php的水珠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!