I created an autocomplete field using JQueryUI and I've stored my data in a flat doc. I can read the values into an array... but I would like to be able to return the alphabetic matches based on the user input. So if the array contains [orange,blue,green,red,pink,brown,black]
and the user types bl then I only return [blue,black]
.
Looking at array_diff()
but without complete matches on the entire value of the array, I'm not sure how to use it... maybe a regular expression thrown in? My two weakest skills array manipulation and regex Thanks for the help!
You don't need to use array_filter
and a custom / lambda function, preg_grep
does the trick:
$input = preg_quote('bl', '~'); // don't forget to quote input string! $data = array('orange', 'blue', 'green', 'red', 'pink', 'brown', 'black'); $result = preg_grep('~' . $input . '~', $data);
array_filter()
, with a callback filtering function based on stripos()
, should do the trick.
For example, if the input is stored in $input
, and your array in $data
:
$input = 'bl'; $data = array('orange', 'blue', 'green', 'red', 'pink', 'brown', 'black');
Filtering to keep only the words that contain $input
(no matter where in the string) could be done this way :
$result = array_filter($data, function ($item) use ($input) { if (stripos($item, $input) !== false) { return true; } return false; }); var_dump($result);
And, here, you'd get :
array 1 => string 'blue' (length=4) 6 => string 'black' (length=5)
Changing the filtering callback, you can :
stripos()
is === 0
strpos()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With