doudu9652 2013-01-11 05:00
浏览 54
已采纳

建议在PHP中搜索数组中的字符串的有效方法

I'm using jQuery autocomplete, following is my code

prg1_view.php

<div id="j_autocomplete">
<label>Search</label><input id="search" type="text">
</div>
$( "#search" ).autocomplete({
source: "prg1.php"      
});

prg1.php

$q = strtolower($_GET['term']);
$q = '/'.$q.'/';

$arr1 = array('a'=> 'apple','b'=> 'boy','p'=> 'pineapple');
$arr2 = array();

foreach($arr1 as $key => $value)
{
    if(preg_match($q, $value))
    array_push($arr2, $value);
}

echo json_encode($arr2);

When I'm trying to search for apple,both apple and pineapple are poping up,expected result is I'm getting but is there any other better approach is have to implement this ?

  • 写回答

1条回答 默认 最新

  • dongzhong5573 2013-01-11 05:03
    关注

    For that kind of incredibly basic string matching, you're better off with a simple

    if (strpos($q, $value) !== FALSE) {
       array_push(...);
    }
    

    and save yourself the regex overhead. And of course, if you only need an exact match against the array's contents and not substrings, there's better ways yet, such as in_array().

    if you insist on regexes, then use preg_grep instead, which does what you're doing without the loop:

    $matches = preg_grep('/'. preg_quote($_GET['term']) . '/', $arr1);
    echo json_encode($matches);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗