Home  >  Article  >  Backend Development  >  How to Filter an Array in PHP Like SQL\'s `LIKE \'%search%\'`?

How to Filter an Array in PHP Like SQL\'s `LIKE \'%search%\'`?

DDD
DDDOriginal
2024-11-04 03:19:31702browse

How to Filter an Array in PHP Like SQL's `LIKE '%search%'`?

Filtering Values from an Array Similar to SQL LIKE '%search%'

Devising an autocomplete field using JQueryUI poses a challenge when it comes to filtering values from an array based on user input. Consider an array containing colors: ['orange', 'blue', 'green', 'red', 'pink', 'brown', 'black']. If the user types 'bl,' the desired output would be ['blue', 'black'].

To achieve this, one might consider using array_diff(), but a more suitable approach exists: preg_grep. This function combines regular expressions with filtering, making it ideal for the task at hand.

Implementation using preg_grep:

<code class="php">$input = preg_quote('bl', '~'); // Don't forget to quote the input string
$data = array('orange', 'blue', 'green', 'red', 'pink', 'brown', 'black');

$result = preg_grep('~' . $input . '~', $data);</code>

In this code, preg_quote is used to escape special characters in the input string. The regular expression '~w ~' matches any word (one or more letters) that contains the inputted string. preg_grep then applies this filter to the data array, resulting in the desired matches.

The above is the detailed content of How to Filter an Array in PHP Like SQL\'s `LIKE \'%search%\'`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn