I have a string describing a [ variable operator value ] structure like this:
type == 'prova' && padposition == "stefano" or 10>var_name
I need to build a regular expression to extract the variable name list:
type
padposition
var_name
to apply a post processing on them (basically converting them into key of a PHP array):
$arr_name['type']
$arr_name['padposition']
$arr_name['var_name']
I've found the way to match string delimited by single or double quotes:
('|")(\w*\w)('|")
but I'm not able (I'm too ignorant!) to negate it or simply to extract any word non single or double quote delimited.
A way to do it (highly readable and easy to maintain):
$str = 'type == \'prova\' && padposition == "stefano" or 10>var_name';
$pattern = <<<'EOD'
~
# you define first the basic elements (as for a lexer) with named groups
(?(DEFINE)
(?<var> [a-z_]\w* ) # variable name
(?<dqstr> (?<=") [^\\"]*+ (?s:\\.[^\\"]*)*+ (?=") ) # double quoted string
(?<sqstr> (?<=') [^\\']*+ (?s:\\.[^\\']*)*+ (?=') ) # single quoted string
(?<string> \g<dqstr> | \g<sqstr> ) # any string
(?<num> [0-9]+(?:\.[0-9]+)? ) # a number
(?<value> \g<string> | \g<num> ) # any value
(?<comp> [!><=]= | =?[><] ) # comparison operator
)
# Then you write the pattern using these named groups
(?J) # allow duplicate named groups
# variable op value
(?<key> \g<var> ) \h* \g<comp> \h* ["']? (?<val> \g<value> ) ['"]?
| # OR
# value op variable
["']? (?<val> \g<value> ) ['"]? \h* \g<comp> \h* (?<key> \g<var> )
~xi
EOD;
if (preg_match_all($pattern, $str, $matches, PREG_SET_ORDER)) {
$arr_name = [];
foreach($matches as $m) {
$arr_name[$m['key']] = $m['val'];
}
print_r($arr_name);
}