0

我有一个 PHP 文件,它将在 txt 文件中搜索并显示结果。

但是,如果单词是用大写字母书写的,并且用户用小写字母搜索相同的单词,PHP 文件将显示 found no matches1

例如:

我在 txt 文件中有 Apple Juice。用户搜索苹果汁。PHP 显示没有找到匹配项,因为它正在寻找完全相同的单词“Apple Juice”,其中包含大写字母。

这是我的代码:

<html>
<head><title>some title</title></head>
<body>

<?php
    if(!empty($_POST['search'])) {
    $file = 'mytxtfile.txt';
    $searchfor = '';
    // the following line prevents the browser from parsing this as HTML.
    header('Content-Type: text/plain');
    $searchfor = $_POST['search'];
    $contents = file_get_contents($file);
    $pattern = preg_quote($searchfor, '/');
    $fullword = '\b\Q' . $w . '\E\b';
    $regex = '/' . $fullword . '(?!.*' . $fullword . ')/i';
    $pattern = "/^.*$pattern.*\$/m";
    if(preg_match_all("/\b([a-z]+[A-Z]+[a-zA-Z]*|[A-Z]+[a-z]+[a-zA-Z]*)\b/", $pattern, $contents, $matches)){
       echo "Population: \n";
       echo implode("\n", $matches[0]);

    }
    else{
       echo "No matches found";
    }
    header('Content-Type: text/html');
    }
?>

  <form method="post" action="">
    <input type="text" name="search" />
    <input type="submit" name="submit" />
  </form>

</body>
</html>

我确实尝试将其添加if(preg_match_all("/\b([a-z]+[A-Z]+[a-zA-Z]*|[A-Z]+[a-z]+[a-zA-Z]*)\b/",到我的代码中,但没有奏效!

任何帮助,将不胜感激。

谢谢

4

2 回答 2

1

这是调整后的来源。这会将搜索字符串和文件内容设置为小写。我还向下移动了 HTML 标头并在搜索逻辑期间启动了输出缓冲区。

<?php
ob_start();
if(!empty($_POST['search'])) {
$file = 'mytxtfile.txt';
$searchfor = '';
// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');
$searchfor = strtolower($_POST['search']); #LOWER CASE THE SEARCH STRING TO
$contents = strtolower(file_get_contents($file)); #MAIN ADDITION TO MAKE IT LOWER CASE
$pattern = preg_quote($searchfor, '/');
$fullword = '\b\Q' . $w . '\E\b';
$regex = '/' . $fullword . '(?!.*' . $fullword . ')/i';
$pattern = "/^.*$pattern.*\$/m";
if(preg_match_all("/\b([a-z]+[A-Z]+[a-zA-Z]*|[A-Z]+[a-z]+[a-zA-Z]*)\b/", $pattern,             $contents, $matches)){
   echo "Population: \n";
   echo implode("\n", $matches[0]);

}
else{
   echo "No matches found";
}
header('Content-Type: text/html');
}
ob_end_flush();
?>
<html>
<head><title>some title</title></head>
<body>

<form method="post" action="">
    <input type="text" name="search" />
    <input type="submit" name="submit" />
</form>

</body>
</html>
于 2013-08-12T02:20:13.637 回答
1

像这样更改您的正则表达式模式:

// The "i" at the end is to make a case-insensitive search
$pattern = "/^.*$pattern.*\$/mi";
于 2013-08-12T02:49:11.733 回答