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_array & array_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.



How can we use the same code for multi dimensional array?
Hey Aneeska,
thx for your article. It helped me a lot. I’m very much interested in further search patterns. For example:
Array values:
table
table_2
tableothertable
I would like a search pattern, that only gives me the values “table” and table_2″. Is that possible?
Hi Tino,
‘/table_?(\d{1})*$/’
Try this. This will match ‘table’, ‘table_’, ‘table_1′ (or any one digit number). It will not match ‘tablesometext’
Or,
‘/table(_2)?$/’
This will match exactly what you want. only ‘table’ and ‘table_2′ and nothing else.
Thanks,
Anees