简体   繁体   中英

PHP case insensitive search through text file

I have this .php file that searches for text from a .txt file and compares it to what the user has typed in. I'm not sure how to make it do a case insensitive search of the .txt file.

<?php
  $search = $_POST['search'];
  $text = file_get_contents('name_list.txt');
  $lines = explode("\n", $text);
  if(in_array($_POST['search'], $lines)){
      echo stristr($search, " is compatible!");
  } else {
      echo stristr($search, " is not compatible!");
  }
?>

Here is the javascript it is linked to:

$(function() {

        $(".search_button").click(function() {
            var searchString = $("#search_box").val();
            var data = 'search='+ searchString;

            if(searchString) {
                // ajax call
                $.ajax({
                    type: "POST",
                    url: "do_search.php",
                    data: data,
                    beforeSend: function(html) {
                        $("#results").html(''); 
                        $("#searchresults").show();
                        $(".word").html(searchString);
                   },
                   success: function(html){
                        $("#results").show();
                        $("#results").append(html);
                  }
                });    
            }
            return false;
        });
    });

Any help/comments appreciated.

I would compare the uncapitalised version of the search and the text files:

<?php
$search = $_POST['search'];
$search_lower = strtolower($search); // make the search lowercase
$text = file_get_contents('name_list.txt');
$text = strtolower($text); // make the text lowercase
$lines = explode("\n", $text);

if(in_array($search_lower, $lines)){
    echo $search . " is compatible!";
} else {
    echo $search . " is not compatible!";
}

You can try using preg_match

<?php
$search = $_POST['search'];
$text = file_get_contents('name_list.txt');

if(preg_match('#'.$search.'#i', $text)){
    echo $search . " is compatible!";
} else {
    echo $search . " is not compatible!";
}

The 'i' flag after the expression delimiter indicates a case insensitive matching.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM