在搜索时,如何输出一条“未找到文件”的提示信息?

编程语言 2026-07-10

在使用URL search.php?q=name+of+file 搜索名为name-of-file.mp3的文件时,当搜索的文件名不存在时,我似乎无法让 else 起作用。找到了文件时,它工作正常。

我到底在做什么错?做了一些修改,但在使用strpos的修改后,当没有找到任何文件时,似乎无法让 "You have no files in this directory" 起作用。我相信这是因为我并不是在找文件……而是q。

<?php
$dir = 'C:\storage\filesfound';
$exclude = array('.', '..');
$q = (isset($_GET['q']))? strtolower($_GET['q']) : '';
        if (!empty($q)) {
        $res = opendir($dir); 
        while(false!== ($file = readdir($res))) { 
        if(strpos(strtolower($file), $q)!== false &&!in_array($file,$exclude)) {  
            echo basename($file, ".mp3") . " &#10073; ";
                } 
                }
                closedir($res);
                }
                else {

                echo "You have no files in this directory.";
                    }
?>

解决方案

使用一个标志变量来判断循环是否找到任何匹配。

$dir = 'C:\storage\filesfound';
$exclude = array('.', '..');
$q = (isset($_GET['q'])) ? strtolower($_GET['q']) : '';
if (!empty($q)) {
    $res = opendir($dir);
    $found = false;
    while (false !== ($file = readdir($res))) {
        if (str_contains(strtolower($file), $q) && !in_array($file, $exclude)) {
            echo basename($file, ".mp3") . " &#10073; " . "<br>" . 'In this directory a collection of your files.';
            $found = true;
        }
    }
    closedir($res);
    if (!$found) {
        echo "No matching files found.";
    }
} else {
    echo 'Search string is empty.';
}

我也修正了 else 块中的错误信息,使其与 empty($q) 条件相匹配。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章