1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| $pattern = <<<'EOD'
~
# main pattern
(?=[-"'</.)]) # first character discrimination
(?: # contigous to a previous match
\G (?!\A) # contigous, but not the start of the string
(?: \. \g<ns>* (?= (?<cont>") (?<rsq>')? ) | \) (*ACCEPT))
| # or the prefix
->query \g<ns>* \( \g<ns>* \K
| # skip strings and comments
\g<str> (*SKIP) (*F)
|
\g<c> (*SKIP) (*F)
)
(?<prestr> \g<dqstr> (?:(?<= =(?<lsq>')" | =" ) | \) (*ACCEPT)) )
\g<ns>* \. \g<ns>*
(?<expr>
(?:(?!\.) \g<nb>)*+
(?:\g<bracket> (?:(?!\.) \g<nb>)* )*+
(?:\.(?-1))*? (?= \.\g<ns>*" | \) )
)
# subpatterns definitions
(?(DEFINE)
# brackets
(?<nb> [^][)(}{<'"] | \g<str> | \g<ns> | < )
(?<roundB> \( \g<nb>*+ (?:\g<bracket> \g<nb>*)*+ \) )
(?<squareB> \[ \g<nb>*+ (?:\g<bracket> \g<nb>*)*+ ] )
(?<curlyB> { \g<nb>*+ (?:\g<bracket> \g<nb>*)*+ } )
(?<bracket> \g<roundB> | \g<squareB> | \g<curlyB> )
# strings
(?<dqstr> " [^\\"]*+ (?s:\\.[^\\"]*)*+ " )
(?<sqstr> ' [^\\']*+ (?s:\\.[^\\']*)*+ ' )
(?<heredoc> <<<('?)([^\W\d]\w*)\g{-2}\R (?>.*\R)*? \g{-1} ;? $ )
(?<str> \g<dqstr> | \g<sqstr> | \g<heredoc>)
# comments & whitespaces
(?<c> \Q/*\E [^*]*+ (?:\*+(?!/)[^*]*)*+ (?: \Q*/\E | \z ) | //.*$ )
(?<ns> \g<c> | \s+ ) # non significant
)
~mx
EOD;
$test_string = <<<'EOD'
$x->query("select aa from bb where (bb='".$t['a']."') and cc=".$t['b']." and (lasuite=2)");
$str = <<<'TOTO'
$x->query("select aa from bb where (bb='".$t['a']."') and cc=".$t['b']." and (lasuite=2)");
TOTO;
/* $x->query("select aa from bb where (bb='".$t['a']."') and cc=".$t['b']." and (lasuite=2)"); */
// $x->query("select aa from bb where (bb='".$t['a']."') and cc=".$t['b']." and (lasuite=2)");
$x->query("select aa from bb where (bb='".$t['a'] . $a ."') and cc=".$t['b'] );
$x->query("select aa from bb where (bb='".$t['a'] . ($a->property/2*($b[$d[18].$e[1]]+($c/2))) ."') and cc=".$t['b'] );
$x->query(//commentaire
"select aa from bb where (bb='".$t['a']
. /*commentaire*/ "') and cc=".$t['b']." and (lasuite=2)");
$x->query("select aa from bb where (bb='".$t['a']."') and cc=".$t['b']." and (lasuite=2)");
$x->query("select aa from bb where (bb=?) and cc=? and (lasuite=2)",array($t['a'],$t['b']));
EOD;
$store = [];
$result = preg_replace_callback($pattern, function ($m) use (&$store) {
if ( !empty($m['expr']) ) {
$store[] = trim($m['expr']);
return substr($m['prestr'],
!empty($m['cont']) + !empty($m['rsq']),
-1 - !empty($m['lsq'])
) . '?';
} else {
$values = implode(', ', $store);
$store = [];
return (empty($m['prestr']) ? '"' : substr($m['prestr'], 1, -1))
. ', array(' . $values . '))';
}
}, $test_string);
echo $result; |
Partager