How to split requests using regex in php

Suppose I have the following line:

insert into table values ('text1;'); insert into table values ('text2')

How to break these requests (receive each separate request) using regular expressions?

I found a very similar problem: Use regex to search for a specific string not in the html tag ... but it uses a solution specific to .NET .: for the search (in php it complains that it is not a fixed length).

I would be very grateful if anyone could give me some advice on how to deal with this problem.

+3
source share
4 answers

, , . , SQL , , , . (, .)

100% - , SQL, this. ( " SQL" PHP ". , .)


EDIT:

, , . , - , , , . backrefs .

- , , :

preg_match_all("/(?:([^']*'){2})*[^']*;/U", str_replace("\\'", "\0\1\2", $input), $matches);
$output = array_map(function($str){ return str_replace("\0\1\2", "\\'", $str); }, $matches[0]);

, , , \0\1\2. . , . . ( , PHP 5.3.)

, , .

+1

SQL, , .

regexp , .

/.+?\'.+?\'.*?;|.+?;/

:

/.+?[^\\\\]\'.+?[^\\\\]\'.*?;|.+?;/

.

/.+?(?:[^\\]\'.+?[^\\]\')+.*?;|.+?;/

:

('text1; \' ',' 2 '); ('text2'); test3 ('cookie \' ',' fly ');

:

('text1; \' ',' 2 ');

('text2');

test3 ('cookie \' ',' fly ');

, . SQL. .

+1

?

explode ('', $query) .

, text1 text2 regexp, preg_match ('/(\' ([\ w] +)\')/', $query, $matches), $matches [1] .

preg_match_all ('/([\ w] + ([\ w \';] +))/', $query, $matches) .

0

Regex . :

function splitQuery($query) {
    $open = false;
    $buffer = null;
    $parts = array();
    for($i = 0, $l = strlen($query); $i < $l; $i++) {
        if ($query[$i] == ';' && !$open) {
            $parts[] = trim($buffer);
            $buffer = null;
            continue;
        }
        if ($query[$i] == "'") {
            $open = ($open) ? false: true;
        }

        $buffer .= $query[$i];
    }

    if ($buffer) $parts[] = trim($buffer);
    return $parts;
}

:

$str = "insert into table values ('text1;'); insert into table values ('text2')";
$str = splitQuery($str);
print_r($str);

:

Array
(
    [0] => insert into table values ('text1;')
    [1] => insert into table values ('text2')
)
0

Source: https://habr.com/ru/post/1771012/


All Articles