Filtering Array Values Like SQL LIKE '%search%' Using PHP
To implement an autocomplete feature using JQueryUI, retrieving alphabetic matches from an array based on user input is essential. Consider an array ["orange", "blue", "green", "red", "pink", "brown", "black"]. If the user enters "bl," you want to display only ["blue", "black"].
Instead of using array_filter with a custom function, a more efficient solution is to employ the preg_grep function, which allows for filtering using regular expressions.
Example:
<code class="php">$input = preg_quote('bl', '~'); // Protect against regex special characters $data = array('orange', 'blue', 'green', 'red', 'pink', 'brown', 'black'); $result = preg_grep('~' . $input . '~', $data); print_r($result); // Output: Array ( [0] => blue [1] => black )</code>
Explanation:
The above is the detailed content of How to Filter Array Values Like SQL LIKE \'%search%\' Using PHP?. For more information, please follow other related articles on the PHP Chinese website!