Current Location: Home> Latest Articles> How to output $matches to view the specific structure and content of regular matches?

How to output $matches to view the specific structure and content of regular matches?

M66 2025-06-02

In PHP, when using regular expressions for pattern matching, the preg_match() or preg_match_all() functions are usually used. These functions store the matching results in the $matches variable. By looking at the contents of the $matches variable, we can understand how regular expressions match input strings.

This article will demonstrate how to output the $matches variable to see the specific structure and content of regular matches. We will also discuss how to use the print_r() or var_dump() functions effectively to check the $matches array.

Regular matching basics

In PHP, commonly used regular matching functions are:

The syntax of these two functions is as follows:

 preg_match($pattern, $subject, $matches, $flags = 0, $offset = 0);
preg_match_all($pattern, $subject, $matches, $flags = 0, $offset = 0);

Where $pattern is a regular expression, $subject is the string to be matched, and $matches is an array used to store matching results.

Example: How to output $matches variable

Suppose we have the following PHP code to extract the domain name part in a URL through a regular expression. We will use the preg_match() function and output the contents of the $matches variable.

 <?php
// Define regular expressions,For matching URL
$pattern = "/https?:\/\/([a-zA-Z0-9.-]+)/";

// Input URL String
$url = "https://www.example.com/path/to/resource";

// use preg_match() Perform regular matching
preg_match($pattern, $url, $matches);

// Output $matches Contents
print_r($matches);
?>

Code parsing

  1. $pattern is a regular expression, https?:\/\/([a-zA-Z0-9.-]+) , which is used to match URLs.

  2. $url is the string to be matched, here we use https://www.example.com/path/to/resource .

  3. The preg_match() function performs regular matching and stores the matched results in the $matches array.

  4. Finally, we use the print_r() function to output the contents of the $matches array.

Output result

After running the above code, the output may be as follows:

 Array
(
    [0] => https://www.example.com
    [1] => www.example.com
)

Explain the output

  • $matches[0] contains the complete matching result, i.e. the entire URL ( https://www.example.com ).

  • $matches[1] contains the result of the first capture group, namely the domain name part ( www.example.com ).

How to replace the domain name in the URL

If you want to replace the domain name in the URL with m66.net , you can replace it after the regular expression matches. For example: