What are the advantages and disadvantages of using regex versus other methods, such as foreach loops, to parse PHP code strings?

When parsing PHP code strings, using regex can be advantageous because it allows for more flexible and powerful pattern matching capabilities. However, regex can be complex and difficult to understand for beginners. On the other hand, using foreach loops may be simpler and easier to implement, but it may not be as efficient or precise as regex for certain parsing tasks.

// Using regex to parse PHP code strings
$code = '<?php echo "Hello World"; ?>';
preg_match('/<\?php\s(.*?)\s\?>/s', $code, $matches);
echo $matches[1];

// Using foreach loop to parse PHP code strings
$code = '<?php echo "Hello World"; ?>';
$lines = explode("\n", $code);
foreach($lines as $line){
    if(strpos($line, 'echo') !== false){
        echo substr($line, strpos($line, 'echo')+5, -2);
    }
}