Home  >  Article  >  Backend Development  >  How to Achieve SQL LIKE \'%search%\' Functionality in PHP Arrays?

How to Achieve SQL LIKE \'%search%\' Functionality in PHP Arrays?

DDD
DDDOriginal
2024-11-04 11:02:02546browse

How to Achieve SQL LIKE '%search%' Functionality in PHP Arrays?

Similar SQL Filtering in PHP: Returning Matches with Partial Text

Filtering values from an array based on a partial text search, similar to SQL's LIKE '%search%' query, can be an essential task in many programming scenarios. In PHP, achieving this using arrays requires specialized techniques.

Let's consider the example provided. Given an array containing color names, the goal is to return only the colors that partially match the user's input text. For instance, with an input of "bl", the expected output would be ["blue", "black"] from the input array ["orange", "blue", "green", "red", "pink", "brown", "black"].

Using Regular Expressions with preg_grep

Instead of using array_filter with a custom lambda function, a simpler and more efficient approach is to employ the preg_grep function. It combines the power of regular expressions with array filtering:

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

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

In this code:

  • preg_quote protects the input string by escaping special characters like ., ?, and *.
  • preg_grep uses the PHP ~ delimiter for regex, and the pattern ~' . $input . '~ matches any string that contains the input substring bl.
  • The resulting $result array will only contain elements that partially match the input, i.e., blue and black.

The above is the detailed content of How to Achieve SQL LIKE \'%search%\' Functionality in PHP Arrays?. 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