Home  >  Article  >  Backend Development  >  How to Filter Array Values Like SQL LIKE \'%search%\' Using PHP?

How to Filter Array Values Like SQL LIKE \'%search%\' Using PHP?

Susan Sarandon
Susan SarandonOriginal
2024-11-04 04:32:29830browse

How to Filter Array Values Like SQL LIKE '%search%' Using PHP?

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:

  • preg_quote('bl', '~') escapes special characters in the input string, ensuring that it is treated literally in the regular expression.
  • The regular expression ~ . $input . ~ searches for elements in the array that contain the input string "bl" anywhere within the value.
  • preg_grep applies this regular expression filter to the $data array, returning an array containing only matches that satisfy the condition.

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!

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