使用glob排除index.PHP的PHP代码 问题
我试图显示名为../health/ 在这个文件中有一个index.php文件和另外118个名为php文件的文件。 我想随机显示健康文件夹中的一个文件,但我希望它排除index.php文件 下面的代码有时包含index.php文件。 我还尝试修改$exclude行以显示../health/index.php,但仍然没有成功使用glob排除index.PHP的PHP代码 问题,php,arrays,glob,Php,Arrays,Glob,我试图显示名为../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(
<?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);
?
此代码还包括index.php文件,但它没有显示页面,而是将页面显示为错误。首先想到的是
array\u filter()
,实际上它是preg\u 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);
为了赞美杰克的回答,使用
preg\u grep()
你还可以:
$files = array_values( preg_grep( '/^((?!index.php).)*$/', glob("*.php") ) );
这将返回一个数组,其中包含与
index.php
直接不匹配的所有文件。这就是如何在不使用PREG\u GREP\u invert
标志的情况下反转对index.php的搜索。我的目录文件列表是:
$ee = glob(__DIR__.DIRECTORY_SEPARATOR.'*',GLOB_BRACE);
结果
我编写代码test.php并运行它
只需像这样使用glob:
$ee = glob(__DIR__.DIRECTORY_SEPARATOR.'[!{index}]*',GLOB_BRACE);
print_r($ee);
将其用于排除文件和目录,名称以索引开头
结果
对于排除文件名,它以Old
结果
对于您,我在PHP8.0exclude files index.php中测试了这段代码
您好,谢谢您的回复,但我对php有点陌生,仍在学习基础知识,您的代码在我的代码中的位置如何。非常感谢mally@user1649416我已经更新了答案,我想现在会更有意义:)我知道你有比教我这样的傻瓜更好的事情要做,但我还是迷路了@user1649416嗯,好的,再次更新;这很清楚,希望能有所帮助:)非常感谢您的帮助,我真的很感激。您好,谢谢您的回答,事实上我在jacks代码中使用了您的代码,效果非常好,我感谢您对此的输入。我编辑了您的问题,删除了您添加的答案(解决方案)。因为您是SO新手,所以它的工作方式是选择最能解决问题的答案,然后单击旁边的复选标记接受它。
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
)
$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
)
$ee = glob(__DIR__.DIRECTORY_SEPARATOR.'*[!{index}].php',GLOB_BRACE);
print_r($ee);