PHP 函数 strpos() 和 stristr()

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


//index.php



<?php


?>


<!DOCTYPE html>

<html>

<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;

?>


慕田峪9158850
浏览 136回答 1
1回答

摇曳的蔷薇

在这种情况下,您应该进行严格的比较,if&nbsp;(strpos($value["name"],&nbsp;$searchText)&nbsp;!==&nbsp;false&nbsp;||&nbsp;strpos($value["surname"],&nbsp;$searchText)&nbsp;!==&nbsp;false){我添加了与false.&nbsp;应该管用。
打开App,查看更多内容
随时随地看视频慕课网APP