We write the expressions of the contents that we want to capture and separate in regular expressions in parentheses. We will access the contents that match the expressions written in parentheses, thanks to the preg_match_all function. This function includes the setting g which allows it to scan all content, so when using preg_match_all you don’t need to type in the setting g (global).

Apart from theoretical information and examples, I think we can grasp it better by looking at their use in real life. We can write an expression to capture the title of the site between the title tag of a site.

<?php
$pattern = '/<title>(.+)<\/title>/i';
$content = file_get_contents('https://baransel.dev');
 
preg_match_all($pattern, $content, $results);
 
print_r($results);

The screen output will be as follows;

Array
(
    [0] => Array
        (
            [0] => <title>Baransel Arslan</title>
        )

    [1] => Array
        (
            [0] => Baransel Arslan
        )

)

The first element of the array in the $results variable; Returns the array of contents matching the entered expression. The next elements give an array of contents that match the expressions we grouped with parentheses. In other words, we will look at the 2nd element to get the characters we put in parentheses between the title tags.

The second element is an array in itself, so if there are more than one matches, it will also give them sequentially.