我有一个表单,用户可以在其中输入文件名。它成功地遍历所有目录,查找与用户搜索输入相匹配的相关pdf文件。
当它找到匹配时,它正确地回显'it matches'并跳出foreach循环。但是,在匹配正确的文件之前,它也会正确地对找到的所有文件声明"不匹配"。所以我会得到一个很长的列表,上面是'not a match ',后面跟着'it matches'。
如果我回" "而不是'not a match',它工作得很好,不显示任何东西,但我想告诉用户只有一次,他们所输入的不匹配。我肯定我忽略了一些基本的东西,但如果能提供任何帮助,我将非常感激。
这是我的代码。
<?php
if (isset($_POST['submit']) && !empty($_POST['target'])) {
$searchInput = $_POST['target'];
$it = new RecursiveDirectoryIterator("/myDirectory/");
foreach(new RecursiveIteratorIterator($it) as $file) {
$path_info = pathinfo($file);
$extension = $path_info['extension'];
if (strcmp("pdf", $extension) == 0) {
$lowerInput = strtolower($searchInput);
if (!empty($path_info)) {
$string = strtolower($path_info['filename']);
if(preg_match("~b" . $lowerInput. "b~", $string)) {
echo "it matches <br>";
break;
} else {
if (!preg_match("~b" . $lowerInput . "b~", $string)) {
echo "not a match <br>";
}
}
}
}
} //end foreach
} // end if submit pressed
?>
<html>
<head>
</head>
<body>
<h3>Search Files</h3>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="searchform">
Type the File You Require:<br><br>
<input id="target" type="text" name="target" required >
<br>
<input id="submit" type="submit" name="submit" value="Search" >
</form>
</body>
</html>
我省略了一些代码,只显示了重要的部分。基本上只是设置一个变量,并在foreach
完成时回显它一次。
$msg="Not a match <br>" ;
foreach(new RecursiveIteratorIterator($it) as $file) {
...
if(preg_match("~b" . $lowerInput. "b~", $string)) {
$msg = "it matches <br>" ;
break ;
}
// no need for an else clause, "not a match" is default finding
}// end of foreach
echo $msg ;