In this post I'll provide you with three different methods of doing what you ask for. I actually recommend using the last snippet, since it's easiest to comprehend as well as being quite neat in code.


How to get the matching elements of an array

There is a function dedicated for just this purpose, preg_grep. It will take a regular expression as first parameter, and an array as the second.

See the below example:

$haystack = array (
  'say hello',
  'hello stackoverflow',
  'hello world',
  'foo bar bas'
);

$matches  = preg_grep ('/^hello (\w+)/i', $haystack);

print_r ($matches);

output

Array
(
    [1] => hello stackoverflow
    [2] => hello world
)

Documentation

  • PHP: preg_grep - Manual

How to extract only the matching text from array elements?

array_reduce with preg_match can solve this issue in clean manner; see the snippet below.

$haystack = array (
  'say hello',
  'hello stackoverflow',
  'hello world',
  'foo bar bas'
);

function _matcher (str) {
  if (preg_match ('/^hello (\w+)/i', matches))
    matches[1];

  return $m;
}

// N O T E :
// ------------------------------------------------------------------------------
// you could specify '_matcher' as an anonymous function directly to
// array_reduce though that kind of decreases readability and is therefore
// not recommended, but it is possible.

$matches = array_reduce ($haystack, '_matcher', array ());

print_r ($matches);

output

Array
(
    [0] => stackoverflow
    [1] => world
)

Documentation

  • PHP: array_reduce - Manual
  • PHP: preg_match - Manual

Using array_reduce seems tedious, is there another way?

Yes, and this one is actually cleaner though it doesn't involve using any pre-existing array_* or preg_* function.

Wrap it in a function if you are going to use this method more than once.

$matches = array ();

foreach ($haystack as $str) 
  if (preg_match ('/^hello (\w+)/i', m))
    $matches[] = $m[1];

Documentation

  • PHP: preg_match - Manual
Answer from Filip Roséen on Stack Overflow
🌐
PHP
php.net › manual › en › function.preg-match-all.php
PHP: preg_match_all - Manual
Can be a combination of the following flags (note that it doesn't make sense to use PREG_PATTERN_ORDER together with PREG_SET_ORDER): ... Orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on.
🌐
SitePoint
sitepoint.com › php
Using preg_match with an array - PHP - SitePoint Forums | Web Development & Design Community
April 22, 2013 - Hi I’m afraid I have a pretty basic knowledge of PHP. I’ve inherited a site with some php as follows: if ($po = $product->GetLink) {$iext = preg_match ("/dwg/", $po) ? 'dwg' : 'pdf'; ?> .............. } I understand this to be $po is the file name $iext is the value ‘dwg’ if the string ‘dwg’ appears in $po else $iext is the value ‘pdf’. This allows me use the value $iext in my html - assiging a css class to the item for styling.
Discussions

php - How to search in an array with preg_match? - Stack Overflow
How do I search in an array with preg_match? Example: name', 'this') , $match) ) { //Excelent!! $items[]... More on stackoverflow.com
🌐 stackoverflow.com
preg_match an array as pattern
I'm trying to preg_match $text for specific words, defined in an array.$text = "PHP is a programming language of choice"; $text = "This is a function written in a programming language called PHP."; $words = array("/java/", "/PHP/", "/html/"); for ($i = 0; $i More on forums.phpfreaks.com
🌐 forums.phpfreaks.com
4
January 15, 2015
Does preg_match() work against arrays, or do I need to split the array into lines first?
In general, but especially in your situation, it's really helpful to learn how to use the manual on php.net In this case: https://www.php.net/manual/en/function.preg-match.php You can see the first two arguments should be strings, not an array. Now, there's also the question of: what do you want to accomplish? Let's say your array has three elements. Two match. Do you expect true or false? What if one matches? Maybe you are looking for array_filter? (I don't think so though...) More on reddit.com
🌐 r/PHPhelp
4
1
April 21, 2021
How do you perform a preg_match where the pattern is an array, in php? - Stack Overflow
I have an array full of patterns that I need matched. Any way to do that, other than a for() loop? Im trying to do it in the least CPU intensive way, since I will be doing dozens of these every mi... More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 6
201

In this post I'll provide you with three different methods of doing what you ask for. I actually recommend using the last snippet, since it's easiest to comprehend as well as being quite neat in code.


How to get the matching elements of an array

There is a function dedicated for just this purpose, preg_grep. It will take a regular expression as first parameter, and an array as the second.

See the below example:

$haystack = array (
  'say hello',
  'hello stackoverflow',
  'hello world',
  'foo bar bas'
);

$matches  = preg_grep ('/^hello (\w+)/i', $haystack);

print_r ($matches);

output

Array
(
    [1] => hello stackoverflow
    [2] => hello world
)

Documentation

  • PHP: preg_grep - Manual

How to extract only the matching text from array elements?

array_reduce with preg_match can solve this issue in clean manner; see the snippet below.

$haystack = array (
  'say hello',
  'hello stackoverflow',
  'hello world',
  'foo bar bas'
);

function _matcher (str) {
  if (preg_match ('/^hello (\w+)/i', matches))
    matches[1];

  return $m;
}

// N O T E :
// ------------------------------------------------------------------------------
// you could specify '_matcher' as an anonymous function directly to
// array_reduce though that kind of decreases readability and is therefore
// not recommended, but it is possible.

$matches = array_reduce ($haystack, '_matcher', array ());

print_r ($matches);

output

Array
(
    [0] => stackoverflow
    [1] => world
)

Documentation

  • PHP: array_reduce - Manual
  • PHP: preg_match - Manual

Using array_reduce seems tedious, is there another way?

Yes, and this one is actually cleaner though it doesn't involve using any pre-existing array_* or preg_* function.

Wrap it in a function if you are going to use this method more than once.

$matches = array ();

foreach ($haystack as $str) 
  if (preg_match ('/^hello (\w+)/i', m))
    $matches[] = $m[1];

Documentation

  • PHP: preg_match - Manual
2 of 6
8

Use preg_grep

$array = preg_grep(
    '/(my\n+string\n+)/i',
    array( 'file' , 'my string  => name', 'this')
);
🌐
PHP Freaks
forums.phpfreaks.com › php coding › regex help
preg_match an array as pattern - Regex Help - PHP Freaks
January 15, 2015 - I'm trying to preg_match $text for specific words, defined in an array.$text = "PHP is a programming language of choice"; $text = "This is a function written in a programming language called PHP."; $words = array("/java/", "/PHP/", "/html/"); for ($i = 0; $i
🌐
W3Schools
w3schools.com › php › func_regex_preg_match_all.asp
PHP preg_match_all() Function
In this example, each element in the matches array has all of the matches for one of the groupings of the regular expression. <?php $str = "abc ABC"; $pattern = "/((a)b)(c)/i"; if(preg_match_all($pattern, $str, $matches, PREG_PATTERN_ORDER)) { print_r($matches); } ?> Try it Yourself »
🌐
PHP Tutorial
phptutorial.net › home › php tutorial › php preg_match
PHP preg_match - PHP Tutorial
September 18, 2021 - preg_match( string $pattern, string $subject, array &$matches = null, int $flags = 0, int $offset = 0 ): int|falseCopy
🌐
Reddit
reddit.com › r/phphelp › does preg_match() work against arrays, or do i need to split the array into lines first?
r/PHPhelp on Reddit: Does preg_match() work against arrays, or do I need to split the array into lines first?
April 21, 2021 -

This is an odd situation, but I'm having to learn to and start writing in PHP before I even have access to a machine that has any way of running/testing PHP code. I have a line where I basically want to do this:

if (preg_match($check_for, $check_in)){
  yadda_yadda();
}

But in this case $check_in is an array. Will that work, or do I need to split the array into individual lines and then preg_match() against the individual lines? I suspect the latter, but want to confirm before I go through the trouble of writing that code.

TIA!

Top answer
1 of 2
2
In general, but especially in your situation, it's really helpful to learn how to use the manual on php.net In this case: https://www.php.net/manual/en/function.preg-match.php You can see the first two arguments should be strings, not an array. Now, there's also the question of: what do you want to accomplish? Let's say your array has three elements. Two match. Do you expect true or false? What if one matches? Maybe you are looking for array_filter? (I don't think so though...)
2 of 2
1
If you're dealing with an array of strings and you're just checking to see if ANY of the elements INDIVIDUALLY match, then you'll have to loop through it: foreach($check_in as $check_in_element) // Loop through each string in $check_in { if(preg_match($check_for, $check_in_element)) { yadda_yadda(); break; // Using break will exit out the loop early so yadda_yadda() doesn't run for every matching array element. } } If the regular expression is simple and doesn't rely on any positional elements (e.g. "^foo" to check for "foo" at the very beginning of a string), then you could also use implode() to temporarily concatenate all of the strings together and then match against the full string: if(preg_match($check_for, implode(" ",$check_in)) { yadda_yadda(); } So if your $check_in array had 3 elements: "foo", "bar", "fox", it would be the same as doing: if(preg_match($check_for, "foo bar fox") { yadda_yadda(); } But again, if your regex needs to be applied against every individual string in the array, then the first code sample would work.
Top answer
1 of 7
25

First of all, if you literally are only doing dozens every minute, then I wouldn't worry terribly about the performance in this case. These matches are pretty quick, and I don't think you're going to have a performance problem by iterating through your patterns array and calling preg_match separately like this:

$matches = false;
foreach ($pattern_array as $pattern)
{
  if (preg_match($pattern, $page))
  {
    $matches = true;
  } 
}

You can indeed combine all the patterns into one using the or operator like some people are suggesting, but don't just slap them together with a |. This will break badly if any of your patterns contain the or operator.

I would recommend at least grouping your patterns using parenthesis like:

foreach ($patterns as $pattern)
{
  $grouped_patterns[] = "(" . $pattern . ")";
}
$master_pattern = implode($grouped_patterns, "|");

But... I'm not really sure if this ends up being faster. Something has to loop through them, whether it's the preg_match or PHP. If I had to guess I'd guess that individual matches would be close to as fast and easier to read and maintain.

Lastly, if performance is what you're looking for here, I think the most important thing to do is pull out the non regex matches into a simple "string contains" check. I would imagine that some of your checks must be simple string checks like looking to see if "This Site is Closed" is on the page.

So doing this:

foreach ($strings_to_match as $string_to_match)
{
  if (strpos($page, $string_to_match) !== false))
  {
    // etc.
    break;
  }
}
foreach ($pattern_array as $pattern)
{
  if (preg_match($pattern, $page))
  {
    // etc.
    break;
  } 
}

and avoiding as many preg_match() as possible is probably going to be your best gain. strpos() is a lot faster than preg_match().

2 of 7
16
// assuming you have something like this
$patterns = array('a','b','\w');

// converts the array into a regex friendly or list
$patterns_flattened = implode('|', $patterns);

if ( preg_match('/'. $patterns_flattened .'/', $string, $matches) )
{
}

// PS: that's off the top of my head, I didn't check it in a code editor
Find elsewhere
🌐
BCCNsoft
doc.bccnsoft.com › docs › php-docs-7-en › function.preg-match.html
Perform a regular expression match
int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )
🌐
A Star Trek Timeline
macs.hw.ac.uk › ~hwloidl › docs › PHP › function.preg-match.html
preg_match
Note that this changes the return ... is available since PHP 4.3.0 . The flags parameter is available since PHP 4.3.0 . preg_match() returns the number of times pattern matches....
🌐
Zend
php-legacy-docs.zend.com › manual › php5 › en › function.preg-match
Perform a regular expression match
preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] ) : int
🌐
BCCNsoft
doc.bccnsoft.com › docs › php-docs-7-en › function.preg-match-all.html
Perform a global regular expression match
int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG_PATTERN_ORDER [, int $offset = 0 ]]] )
🌐
Tutorialspoint
tutorialspoint.com › php › php_preg_match_all.htm
PHP - Function preg_match_all()
<?php $userinfo = "Name: <b>John Poul</b> <br> Title: <b>PHP Guru</b>"; preg_match_all ("/<b>(.*)<\/b>/U", $userinfo, $pat_array); print $pat_array[0][0]." <br> ".$pat_array[0][1]."\n"; ?>
🌐
Staabm
staabm.github.io › 2024 › 07 › 05 › array-shapes-for-preg-match-matches.html
Array Shapes For Preg Match Matches | My developer experience
July 5, 2024 - Bonus points were in because possible flags are php-version specific. Flags like PREG_UNMATCHED_AS_NULL can also lead to $matches to contain null values. PREG_OFFSET_CAPTURE will lead to a different array-shape, since values will be accompanied by their offset in the input string.
🌐
GeeksforGeeks
geeksforgeeks.org › php › php-preg_match-function
PHP | preg_match() Function - GeeksforGeeks
July 11, 2025 - PHP Array Programs · PHP String Programs · PHP Interview Questions · PHP GMP · Last Updated : 11 Jul, 2025 · This function searches string for pattern, returns true if pattern exists, otherwise returns false.
🌐
Scaler
scaler.com › home › topics › php preg_match() function
PHP preg_match() function - Scaler Topics
June 14, 2023 - This array will be populated with the matched substrings that correspond to any capturing groups defined in the regular expression pattern. The preg_match function in PHP returns an integer value, which represents the number of matches found between the regular expression pattern and the string ...
🌐
Phpmentoring
phpmentoring.org › blog › php-preg-match
PHP Preg_Match() Function - Search A String For Pattern With Regular Expression Match
preg_match( string $pattern, string $subject, array &$matches = null, int $flags = 0, int $offset = 0): int|false
🌐
W3Schools
w3schools.com › php › func_regex_preg_match.asp
PHP preg_match() Function
<?php $str = "Visit W3Schools"; $pattern = "/w3schools/i"; echo preg_match($pattern, $str); ?> Try it Yourself »