PHP code to exclude index.php using glob

后端 未结 2 1042
北恋
北恋 2020-12-15 22:52

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 f

相关标签:
2条回答
  • 2020-12-15 23:31

    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);
    
    0 讨论(0)
  • 2020-12-15 23:35

    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.

    0 讨论(0)
提交回复
热议问题