All Matches into Subpatterns via Regular Expressions in PHP
Using the function preg_match_all
, you can
split all found matches into subpatterns.
Let's see how it's done.
Suppose, for example, we have a string with domains:
<?php
$str = 'site.ru site123.com my-site.net';
?>
Let's write a regular expression to search for a domain, separating the name and zone into separate subpatterns:
<?php
$reg = '#([a-z0-9_-]+)\.([a-z]{2,})#';
?>
The result will go into the third parameter of the function:
<?php
preg_match_all($reg, $str, $res);
var_dump($res);
?>
As a result, we will get a two-dimensional array. The zero element of this array will contain the zero subpatterns (i.e., what matched the entire regex), the second element will contain the first subpatterns, and so on:
<?php
[
['site.ru', 'site123.com', 'my-site.net'],
['site', 'site123', 'my-site'],
['ru', 'com', 'net'],
]
?>
Given a string with dates:
<?php
$str = '2023-10-29 2024-11-30 2025-12-31';
?>
Find all dates, separating the year, month, and day into separate subpatterns.