dsfdfdfd6576578 2015-06-10 11:09
浏览 88
已采纳

使用正则表达式在SQL查询中分隔指定的值

What I need is to get all the assigned values in a SQL queries. I am only interested in strings and numbers. For example:

SELECT * FROM my_table WHERE ((name="alex" AND age >= 24) OR gender =1) 
AND date = CURDATE() ORDER BY active = 1 LIMIT 1

By using PHP's preg_match I would like to get an array containing the following values:

$values = array(
    'alex'// name , 
    24    //age, 
    1     //gender,
    1     //active
);

I am a beginner with regular expressions and all I have is this:

preg_match_all('/\=\s*?(.*)\s*/', $sqlquery, $matches);

which will return a single match, the one after the first operator found

  • 写回答

2条回答 默认 最新

  • duanao3204 2015-06-10 11:16
    关注

    Something like

    /[a-zA-Z0-9]+\s*[><!]?=\s*(["a-zA-Z0-9]+)(?=\)|\s|$)/
    
    • [a-zA-Z0-9]+ Matches the left side of the equals to

    • \s* Matches zero or more spaces.

    • [><!]? Character class, matches > or < or !

      • ? Quantifier, ensures that the preceding character class occures zero or one time.
    • = Matches the space.

    • (["a-zA-Z0-9]+) Matches the right hand side of equals.

    • (?=\)|\s|$) Positive look ahead. Checks if the right hand side of = is followed by \s or ) or end of string $

    Test

    $string = 'SELECT * FROM my_table WHERE ((name="alex" AND age >= 24) OR gender =1) 
    AND date = CURDATE() ORDER BY active = 1 LIMIT 1';
    
    preg_match_all('/[a-zA-Z0-9]+\s*[><!]?=\s*(["a-zA-Z0-9]+)(?=\)|\s|$)/', $string, $matches);
    print_r($matches[1]);
    // Outputs
    // Array ( [0] => "alex" 
    //         [1] => 24 
    //         [2] => 1 
    //         [3] => 1 )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题