0

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 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.