1 回答

TA貢獻1777條經(jīng)驗 獲得超3個贊
您如果沒有充分利用遞歸函數(shù)。您應(yīng)該使用由表示的 byref 參數(shù),&或者在遞歸時應(yīng)該返回。
這是一個遞歸示例,它只在找到某些東西時返回,不需要第三個參數(shù)。(注意:有深度優(yōu)先和廣度優(yōu)先搜索,如果你有很多文件和/或目錄可能很重要,你應(yīng)該研究一下。)
function get_all_directory_and_files(string $dir, string $unique_code): ?string
{
? ? $dh = new DirectoryIterator($dir);
? ? foreach ($dh as $item) {
? ? ? ? // Move on if this is just a dot file/folder
? ? ? ? if ($item->isDot()) {
? ? ? ? ? ? continue;
? ? ? ? }
? ? ? ? if ($item->isDir()) {
? ? ? ? ? ? // Capture the return and check it
? ? ? ? ? ? $fileName = get_all_directory_and_files($item->getPathname(), $unique_code);
? ? ? ? ? ? if ($fileName) {
? ? ? ? ? ? ? ? return $fileName;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? if ($item->isFile()) {
? ? ? ? ? ? $without_extension = pathinfo($item, PATHINFO_FILENAME);
? ? ? ? ? ? $arrData = explode("_", $without_extension);
? ? ? ? ? ? if (count($arrData) >= 5 && $arrData[4] === $unique_code) {
? ? ? ? ? ? ? ? // Return if found
? ? ? ? ? ? ? ? return $item->getFilename();
? ? ? ? ? ? }
? ? ? ? }
? ? }
? ? return null;
}
這是一個更短的版本,它使用一些本機 PHP 擴展來做同樣的事情。可以清理 RegEx,但它應(yīng)該使您的模式非常明顯。
function get_all_directory_and_files(string $dir, string $unique_code): ?string
{
? ? $di = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
? ? $fi = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::SELF_FIRST);
? ? $unique_code = preg_quote($unique_code, '/');
? ? $ri = new RegexIterator($fi, "/^[^_]+_[^_]+_[^_]+_[^_]+_${unique_code}(\.|_).*?$/", RecursiveRegexIterator::GET_MATCH);
? ? $ri->rewind();
? ? return $ri->current()[0] ?? null;
}
一個不太重復的 RegEx 版本是:
? ? $ri = new RegexIterator($fi, "/^([^_]+_){4}${unique_code}(\.|_).*?$/", RecursiveRegexIterator::GET_MATCH);
- 1 回答
- 0 關(guān)注
- 178 瀏覽
添加回答
舉報