Home > Backend Development > PHP Tutorial > How to Filter Array Values with a SQL-Like \'%search%\' Query in PHP?

How to Filter Array Values with a SQL-Like \'%search%\' Query in PHP?

Mary-Kate Olsen
Release: 2024-11-04 02:07:01
Original
1046 people have browsed it

How to Filter Array Values with a SQL-Like

Filter Array Values Using a SQL-Like "%search%" Query in PHP

When constructing an autocomplete field with JQueryUI, retrieving specific results from an array based on user input can be a challenge. To effectively filter array values based on a partial search string, similar to the SQL LIKE '%search%' query, it's important to understand the nuances of array manipulation and regular expressions. Without using exact matches, the task requires a customized approach.

One solution involves employing the preg_grep function, which enables the use of a regular expression to filter an array. By properly escaping the user input and using the ~ delimiter, a regular expression can be crafted to match any string containing the search string anywhere within it. For example:

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

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

The resulting $result array will contain all elements from $data that contain the sequence 'bl' anywhere in their value, effectively replicating the behavior of a SQL LIKE '%search%' query. By carefully combining array manipulation techniques and regular expressions, you can filter array values in a flexible and efficient manner, enhancing the user experience and accuracy of your autocomplete functionality.

The above is the detailed content of How to Filter Array Values with a SQL-Like \'%search%\' Query in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template