Home > Article > Backend Development > 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:
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!