在PHP中搜索大写和小写单词?

时间:2013-08-12 02:06:10

标签: php

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

但是,如果单词是用大写文本写的,并且用户用小写字母搜索相同的单词,那么PHP文件将显示找不到匹配1

例如:

我在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/",添加到我的代码中,但这不起作用!

任何帮助将不胜感激。

由于

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:1)

像这样改变你的正则表达式:

// The "i" at the end is to make a case-insensitive search
$pattern = "/^.*$pattern.*\$/mi";