PHP code to exclude index.php using glob

我们两清 提交于 2019-12-18 14:52:51

问题


Problem

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.

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

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


回答1:


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');
});

With preg_grep() using PREG_GREP_INVERT to exclude the pattern:

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

It avoids having to use a callback though practically it will likely have the same performance

Update

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



回答2:


To compliment Jack's answer, with preg_grep() you can also do:

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

This will return an array with all files that do NOT match index.php directly. This is how you could invert the search for index.php without the PREG_GREP_INVERT flag.



来源:https://stackoverflow.com/questions/12284170/php-code-to-exclude-index-php-using-glob

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!