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 ?
For that kind of incredibly basic string matching, you’re better off with a simple
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_grepinstead, which does what you’re doing without the loop: