[英]extract values from a query regex
I need to extract the values of a condition (WHERE) and did a regex, but I can not get the values correctly. 我需要提取条件(WHERE)的值并进行正则表达式,但我无法正确获取值。
//Patherns
$regex = "/([a-zA-Z_]+)\s([\<\=\>\s]{0,4})\s+(\".*\")/";
//values to be extracted
$string = 'idCidade >= "bla" OR idEstado="2" and idPais="3"';
//regex function
preg_match_all(
$regex,
$string,
$output
);
//displays the result
echo '<pre>';print_r($output);
//incorrect output
Array
(
[0] => Array
(
[0] => idCidade >= "bla" OR idEstado="2" and idPais="3"
)
[1] => Array
(
[0] => idCidade
)
[2] => Array
(
[0] => >=
)
[3] => Array
(
[0] => "bla" OR idEstado="2" and idPais="3"
)
)
I need the regular expression to export the values to an array like this; 我需要正则表达式将值导出到这样的数组;
//correct output
Array
(
[0] => Array
(
[0] => idCidade >= "bla" OR idEstado="2" and idPais="3"
)
[1] => Array
(
[0] => idCidade
[1] => idEstado
[2] => idPais
)
[2] => Array
(
[0] => >=
[1] => =
[2] => =
)
[3] => Array
(
[0] => "bla"
[1] => "2"
[2] => "3"
)
[4] => Array
(
[0] => "OR"
[1] => "AND"
[2] => ""
)
)
Your mistake was probably the .*
which matches too much. 您的错误可能是匹配过多的
.*
。 You'd need to make it "ungreedy" with appending a question mark: .*?
您需要添加一个问号使它“不舒服”:
.*?
I would however suggest this regex: 但是我建议使用此正则表达式:
'/(OR|AND)?\s*(\w+)\s*([<=>!]+)\s*("[^"]*"|\'[^\']*\'|\d+)/i'
This matches the boolean connector first and optionally, so that you get: 这首先匹配布尔连接器,也可以选择匹配,因此您将获得:
[1] => Array
(
[0] =>
[1] => OR
[2] => and
)
[2] => Array
(
[0] => idCidade
[1] => idEstado
[2] => idPais
)
[3] => Array
(
[0] => >=
[1] => =
[2] => =
)
[4] => Array
(
[0] => "bla"
[1] => "2"
[2] => "3"
)
I've also made it work for SQL-compliant strings and decimals. 我也使它适用于SQL兼容的字符串和小数。 But this is only borderline a job for regex.
但这仅仅是正则表达式的一项工作。 A real parser would be advisable.
建议使用真正的解析器。 (Though I don't know your use case.)
(尽管我不知道您的用例。)
Try this. 尝试这个。 This outputs the exact result you need.
这将输出您需要的确切结果。
<?php //Patherns
$regex = '/([a-zA-Z_]+)\s*([>=<]*)\s*"([^"]*)"\s*(or|and)*/i';
//values to be extracted
$string = 'idCidade >= "bla" OR idEstado="2" and idPais="3"';
//regex function
preg_match_all(
$regex,
$string,
$output
);
//displays the result
echo '<pre>';print_r($output);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.