PHP函数strpos()和stristr()

时间:2019-06-19 10:52:02

标签: php

我需要创建搜索框,但是使用strpos函数存在问题。例如,当我键入Jane时,没有任何结果,searchResult数组为空,但是当我键入ane(不带第一个字符)时,它就起作用了。功能stristr可以正常工作,但是我需要使用strpos()。 这是我的代码,我有3个文件:index.php,script.js,server.php。

//index.php


<?php

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Profit | Homework | AJAX</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<body>
    <input type="text" class="inp">
    <div class="result"></div>
</body>
    <script src="script.js"></script>
</html>


//script.js


$(".inp").on("input", function(){
    let val = $(this).val();
    $.ajax({
        type: "post",
        url: "server.php",
        data: {value: val},
        success: function(r) {
            r = JSON.parse(r);
            console.log(r);
            $(".result").empty();
            r.forEach(function(i){
                $(".result").append(`<div> <h1> ${i.name} </h1> <h2> ${i.surname} </h2> <img src="${i.img}" width="200" heigth="200"> </div>`)
            })
        }
    })
})


//server.php

<?php
    class Search {
        function __construct(){
            $this->arr = [["name" => "Jane", "surname" => "Brown", "img" => "img/manager-1.png"],
                    ["name" => "Bob", "surname" => "Crown", "img" => "img/Business-Man-Clipart-PNG-Image.png"],
                    ["name" => "Mike", "surname" => "Ford", "img" => "img/lending-img.png"]];       

            $this->searchResult = [];

            if ($_SERVER["REQUEST_METHOD"] == "POST") {
                $searchText = $_POST["value"];
                if (strlen($searchText) != 0){
                    foreach ($this->arr as $value) {
                        if (strpos($value["name"], $searchText) || strpos($value["surname"], $searchText)){
                            $this->searchResult[] = $value;
                        }
                    }
                }
                print json_encode($this->searchResult);
            }
        }
    }

    $x = new Search;
?>

1 个答案:

答案 0 :(得分:1)

在这种情况下,您应该进行严格的比较,

if (strpos($value["name"], $searchText) !== false || strpos($value["surname"], $searchText) !== false){

我与false进行了严格的比较。应该可以。