PHP functions strpos() and stristr()



我需要创建搜索框,但 strpos 函数有问题。当我键入,例如,名称简时,则没有结果,searchResult 数组为空,但是当我键入 ane(没有第一个字符(时,它正在工作。函数 stristr 在没有这个问题的情况下工作,但我需要使用 strpos((。这是我的代码,我有 3 个文件:索引.php、脚本.js、服务器.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;
?>

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

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

我添加了与false的严格比较.应该工作。

最新更新