从查询正则表达式中提取值

时间:2011-10-26 19:36:30

标签: php 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] => ""
    )
)

2 个答案:

答案 0 :(得分:3)

你的错误可能是匹配太多的.*。您需要添加一个问号“{ungreedy”:.*?

我会建议这个正则表达式:

'/(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的字符串和小数。但这只是正则表达式的边缘工作。一个真正的解析器是可取的。 (虽然我不知道你的用例。)

答案 1 :(得分:2)

试试这个。这将输出您需要的确切结果。

<?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);