Pockets When Searching via Regular Expressions in PHP
Suppose we have some string containing a domain:
<?php
$str = 'eee site.ru bbb';
?>
Let's find this domain and split it into parts: separate the domain name from its zone. To do this, we will use special pockets of regular expressions.
Pockets are array elements into which parts found by the regex can be placed. In our case, into the first pocket we can put the domain name, and into the second - its zone.
Let's do this. First, let's write a regex that finds the domain in the string:
<?php
$reg = '#[a-z0-9_-]+\.[a-z]{2,}#';
?>
Now let's denote in our regex which parts should go into which pocket. This is done using parentheses. Let's use them to highlight the part of the regex that searches for the domain name, and the part that searches for the domain zone:
<?php
$reg = '#([a-z0-9_-]+)\.([a-z]{2,})#';
?>
Now in the preg_match
function, as the
third parameter, we will specify a variable (any name):
<?php
preg_match($reg, $str, $res);
?>
The specified variable will receive an array with the found pockets. Moreover, the zeroth element of the array will contain the found string, the first element - the first pocket, the second element - the second pocket, and so on:
<?php
preg_match($reg, $str, $res);
var_dump($res); // will output ['site.ru', 'site', 'ru']
?>
Given a string with a date:
<?php
$str = '2025-12-31';
?>
Put the year, month, and day into separate pockets.
Given a string with a filename:
<?php
$str = 'index.html';
?>
Put the filename and its extension into separate pockets.