14

問題

../health/というファイルからランダムなページを表示しようとしています。このファイルには、index.phpファイルとphpファイルという名前の118個の他のファイルがあります。健康フォルダからランダムにファイルを表示したいのですが、index.phpファイルを除外したいと思います。

この次のコードには、index.phpファイルが含まれている場合があります。$exclude行を変更して../health/index.phpを表示しようとしましたが、それでもうまくいきません。

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

私が試した別のコードは次のとおりです

<?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ファイルも含まれていますが、ページを表示するのではなく、ページをエラーとして表示します。

4

3 に答える 3

23

最初に頭に浮かんだのはarray_filter()、実際にはそうでしたがpreg_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);
于 2012-09-05T14:54:16.913 に答える
5

ジャックの答えを褒めるために、preg_grep()あなたと一緒に行うこともできます:

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

これにより、直接一致しないすべてのファイルを含む配列が返されますindex.php。これは、フラグindex.phpなしで検索を逆にする方法です。PREG_GREP_INVERT

于 2012-09-05T14:59:10.003 に答える
1

私のディレクトリファイルリストは次のとおりです。

$ee = glob(__DIR__.DIRECTORY_SEPARATOR.'*',GLOB_BRACE);

結果

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
)

test.phpにコードを書いて実行します

次のようにglobを使用します。

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

除外ファイルの名前はOldで終わります

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

あなたのためにこのコードは私がphp8.0でテストしますファイルindex.phpを除外します

$ee = glob(__DIR__.DIRECTORY_SEPARATOR.'*[!{index}].php',GLOB_BRACE);

print_r($ee);
于 2021-04-01T12:09:17.743 に答える