How can regular expressions (regex) be used in PHP to identify and extract code blocks from a string?

Regular expressions can be used in PHP to identify and extract code blocks from a string by defining a pattern that matches the structure of a code block. By using functions like preg_match_all() or preg_match(), we can search for and extract the code blocks based on the defined pattern. The extracted code blocks can then be processed or manipulated as needed.

$string = "Some text before the code block
{
    int x = 5;
    for(int i = 0; i < 10; i++) {
        cout << i << endl;
    }
}
Some text after the code block";

$pattern = '/\{.*?\}/s'; // Regex pattern to match code blocks

preg_match_all($pattern, $string, $matches);

foreach ($matches[0] as $match) {
    echo "Code block found: " . $match . "\n";
}