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.
In PHP, commonly used regular matching functions are:
preg_match() : Used to perform a regular match.
preg_match_all() : Used to perform multiple regular matches.
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.
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);
?>
$pattern is a regular expression, https?:\/\/([a-zA-Z0-9.-]+) , which is used to match URLs.
$url is the string to be matched, here we use https://www.example.com/path/to/resource .
The preg_match() function performs regular matching and stores the matched results in the $matches array.
Finally, we use the print_r() function to output the contents of the $matches array.
After running the above code, the output may be as follows:
Array
(
[0] => https://www.example.com
[1] => www.example.com
)
$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 ).
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: