- var_dump: documentation ( source)
- array_merge: documentation ( source)
- preg_split: documentation ( source)
<?php
function isQuotedString($token)
{
return in_array($token[0], array('"', "'")) && $token[0] == $token[strlen($token) - 1];
}
function getQueryTokens($query)
{
static $expr = '/("(?:[^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'(?:[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\')/';
$tokens = [];
foreach (preg_split($expr, $query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) as $token) {
if (isQuotedString($token)) {
$tokens[] = $token;
} else {
$tokens = array_merge($tokens, preg_split('/(\?)/', $token, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY));
}
}
return $tokens;
}
var_dump(getQueryTokens("SELECT * FROM foo WHERE 'a' = b AND f = ? AND q IN (?)"));