从查询正则表达式中提取值
我需要提取条件(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"
)
)
我需要正则表达式将值导出到这样的数组;
//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] => ""
)
)
I need to extract the values of a condition (WHERE) and did a regex, but I can not get the values correctly.
//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] => ""
)
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的错误可能是
.*
匹配太多。您需要通过附加问号使其“不贪婪”:.*?
不过,我建议使用此正则表达式:
这首先匹配布尔连接器,并且可选,以便您得到:
我已经还使其适用于 SQL 兼容的字符串和小数。但这对于正则表达式来说只是一个边缘工作。建议使用真正的解析器。 (虽然我不知道你的用例。)
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:
This matches the boolean connector first and optionally, so that you get:
I've also made it work for SQL-compliant strings and decimals. 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.