preg_grep() - Search Array Members

This section provides a tutorial example on how to search for array members with a given regular expression pattern using preg_grep() function.

If you want to search members in an array by a regular expression, you can use the preg_grep() function.

$matches = preg_grep($pattern, $subjects);

where: 
  $pattern: The regular express pattern to search for
  $subjects: The array whose member values will be searched against
  $matches: Array to store matched member values and their keys

Here is an example script that searches a given pattern in an array.

<?php
# preg-grep-search-in-array.php
# Copyright 2009-2024 (c) HerongYang.com. All Rights Reserved.

  $subjects = array(
    "herongyang.com/PHP",
    "w3schools.com/PHP",
    "herongyang.com/Python",
    "w3schools.com/Python"
  );
  $pattern = "/python/i";
  print("Pattern: $pattern\n");
  print("Input subjects:\n"
    .json_encode($subjects, JSON_PRETTY_PRINT)."\n");

  print("Search for elements in array:\n");
  $matches = preg_grep($pattern, $subjects);
  print("Matched subjects:\n"
    .json_encode($matches, JSON_PRETTY_PRINT)."\n");
?>

If you run the above script, you will see the following output:

herong$ php preg-grep-search-in-array.php 

Pattern: /python/i
Input subjects:
[
    "herongyang.com\/PHP",
    "w3schools.com\/PHP",
    "herongyang.com\/Python",
    "w3schools.com\/Python"
]

Search for elements in array:
Matched subjects:
{
    "2": "herongyang.com\/Python",
    "3": "w3schools.com\/Python"
}

Table of Contents

 About This Book

 Introduction and Installation of PHP

 Managing PHP Engine and Modules on macOS

 Managing PHP Engine and Modules on CentOS

 cURL Module - Client for URL

 DOM Module - Parsing HTML Documents

 GD Module - Manipulating Images and Pictures

 MySQLi Module - Accessing MySQL Server

 OpenSSL Module - Cryptography and SSL/TLS Toolkit

PCRE Module - Perl Compatible Regular Expressions

 PCRE Module and C Library

 preg_match() - Regular Expression Match

preg_grep() - Search Array Members

 preg_replace() - Replace Matched Substring

 preg_split() - Split String into Tokens

 preg_quote() - Escape Characters in Pattern

 SOAP Module - Creating and Calling Web Services

 SOAP Module - Server Functions and Examples

 Zip Module - Managing ZIP Archive Files

 References

 Full Version in PDF/EPUB