I have an array with many values and I need to do a search to find all the values that match a pattern. We have functions like in_arrayarray_search in PHP, but these functions basically try to match the exact needle value in the array. I need to use my Regular Expression Pattern and find all the array values that match the regex pattern.

The PHP function preg_grep handles this beautifully. It accepts the Regex pattern and the array to search for as its parameters. It then returns the array consisting of the elements of the input array that match the given pattern. The returned array is indexed using the keys from the input array.

Here is my array:
Array
(
[0] => Armenia
[1] => America
[2] => Algeria
[3] => India
[4] => Brazil
[5] => Croatia
[6] => Denmark
)
I want to find all the countries in the array which start with the letter ‘A’. We need to form a regular expression which will match all the strings starting with letter A.

I have got this simple regular expression: ‘/^A.*/’

Now here is the PHP code to find the values from the Array.

<?php
$array = array('Armenia', 'America', 'Algeria', 'India', 'Brazil', 'Croatia', 'Denmark');
$fl_array = preg_grep('/^A.*/', $array);
echo '<pre>';
print_r($fl_array);
echo '</pre>';
?>
Which then gives you this output:
Array
(
[0] => Armenia
[1] => America
[2] => Algeria
)

Here are some Regular Expression Patterns you could use.

Find whole numbers: ‘/^\d+$/’
Floating numbers: ‘/^\d+\.{1}\d+$/’
Lowercase Words: ‘/^[a-z]+$/’

Play with Regular Expressions and let me know if you have any questions or if you need more patterns. I am planning to publish an article on Regular Expressions soon.

Courtesy : http://ask.amoeba.co.in/php-search-in-an-array-for-values-matching-a-pattern-regex-wildcard/
Tagged with:
 

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Set your Twitter account name in your settings to use the TwitterBar Section.