I know this question have been asked endless times but I can’t find a working solution for my case.
I want to split a string in PHP (5.3) using semicolons as delimiters unless they are between $BODY$ strings. The goal is to split SQL statements where statements can be procedures (postgresql in this case).
Example:
select; start $BODY$ begin; end; $BODY$ lang; update
Should result in:
select start $BODY$ begin; end; $BODY$ lang update
I have been toying with preg_split for a while and cannot find a working solution.
Many thanks
Edit: it must works with multiline inputs (but I can remove line breaks using str_replace before hand)
As no regexps seemed to fit, here is how I did it for the one who are interested:
$length = strlen($sql); $queries = array(); $offset = 0; $last = 0; do { if (($colon = strpos(substr($sql, $offset), ';')) === false) { break; } $colon += $offset; if (($body = strpos(substr($sql, $offset), '$BODY$')) !== false) { $body += $offset; if ($body < $colon) { $offset = $body + strpos(substr($sql, $body + 6), '$BODY$') + 12; continue; } } $queries[] = trim(substr($sql, $last, $colon - $last)); $last = $offset = $colon + 1; } while($offset <= $length);