How can regular expressions be effectively used to parse and extract SQL statements from a string in PHP?

Regular expressions can be effectively used to parse and extract SQL statements from a string in PHP by defining patterns that match SQL statements. By using functions like preg_match_all(), we can search for these patterns in the input string and extract the SQL statements. This allows us to separate SQL statements from other text in the input string.

$inputString = "SELECT * FROM table1; INSERT INTO table2 VALUES (1, 'example');";
$pattern = '/(SELECT.*?;|INSERT.*?;|UPDATE.*?;|DELETE.*?;)/';
preg_match_all($pattern, $inputString, $matches);

foreach($matches[0] as $sqlStatement) {
    echo $sqlStatement . "\n";
}