PHP正则表达式替换SQL查询条件

时间:2011-08-01 06:36:27

标签: php regex

无法弄清楚如何用PHP替换SQL查询中的条件值,

示例:

SELECT * 
FROM table 
WHERE a=1 
and a = '2' 
and a= "3" 
and a LIKE '%a' 
and a LIKE "a%" 
and a < 1 
and a<1 
and a >1 
and a >1 
HAVING a <1

所以期望的输出将是

SELECT * 
FROM table 
WHERE a=? 
and a = ? 
and a= ? 
and a LIKE ? 
and a LIKE ? 
and a < ? 
and a<? 
and a >? 
and a >? 
HAVING a <?

我失败的模式是:

#(like|<|>|=){1}[\s]{0,1}['"\s"]{0,1}(.*?)['"\s"]{0,1}#si

4 个答案:

答案 0 :(得分:1)

你可以在没有模式的情况下做到这一点

类似的东西:

$query = "SELECT * 
FROM table 
WHERE a=%s 
and a = %s 
and a= %s 
and a LIKE %s 
and a LIKE %s 
and a < %s 
and a<%s 
and a >%s 
and a >%s 
HAVING a <%s";

$query = sprintf($query,$arg1,$arg2,$arg3,$arg4,$arg5,$arg6);

$query = sprintf($query,$arrayArgs);

再一个想法

$query = preg_replace("((.+)(like|<|>|<>|=)(.+)(\s*,|\n|$))Ui","$1$2'?'$4",$query);

答案 1 :(得分:0)

认为这应该做,只需用“?”替换每个匹配(不带引号:)

((?<=like)|(?<=<)|(?<=>)|(?<==))\s*[^\s]+(\s|$)(.(?!where))*

答案 2 :(得分:0)

或者你可以简单地使用替换功能,因为正则表达式在php中很慢而且替换会给你带来巨大的速度提升!

$query = '...';
$query = str_replace('1', '?', $query);
$query = str_replace('2', '?', $query);
$query = str_replace('3', '?', $query);
$query = str_replace('4', '?', $query);
...

答案 3 :(得分:0)

preg_replace("/(LIKE|<|>|<>|=|IS(?: NOT)?|(?:NOT )?IN)\s*(([\"'\(]).*?\3|[^\s]+)/si", "$1 ?", $query);

严格要求围绕值匹配开头和结尾引号(如果存在),还要匹配其他一些运算符和NULL值之类的东西。

但它并不完美,所以要小心


编辑:这是一个更全面的处理IN ( ... )条款的 但尽管如此:弄乱查询仍然很危险。最糟糕的情况是你不小心创建了自己的sql注入

$pattern = '/(LIKE|<|>|<>|=|IS(?: NOT)?|(?:NOT )?IN)
  \s*
  (
    (["\'])     # capture opening quote
    .*?
    (?<![^\\\]\\\)\3  # closing quote
  |
    \(          # opening parenthesis
      [^\)]*
    \)          # closing parenthesis
  |
    [^\s]+      # any other contiguous string
  )/six';

preg_replace($pattern, "$1 ?", $query);