[英]extract values from a query regex
我需要提取條件(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] => ""
)
)
您的錯誤可能是匹配過多的.*
。 您需要添加一個問號使它“不舒服”: .*?
但是我建議使用此正則表達式:
'/(OR|AND)?\s*(\w+)\s*([<=>!]+)\s*("[^"]*"|\'[^\']*\'|\d+)/i'
這首先匹配布爾連接器,也可以選擇匹配,因此您將獲得:
[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"
)
我也使它適用於SQL兼容的字符串和小數。 但這僅僅是正則表達式的一項工作。 建議使用真正的解析器。 (盡管我不知道您的用例。)
嘗試這個。 這將輸出您需要的確切結果。
<?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.