为了账号安全,请及时绑定邮箱和手机立即绑定

PHP 函数 strpos() 和 stristr()

PHP 函数 strpos() 和 stristr()

PHP
慕田峪9158850 2021-08-28 15:32:25
我需要创建搜索框,但是使用 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;?>
查看完整描述

1 回答

?
摇曳的蔷薇

TA贡献1793条经验 获得超6个赞

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

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

我添加了与false. 应该管用。


查看完整回答
反对 回复 2021-08-28
  • 1 回答
  • 0 关注
  • 135 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号