求高手帮忙写一个php分解sql语句匹配正则

vgy12304 2012-10-18 10:26:50
需要分解的sql语句:

select * from tjw_person where personname like '%南京%' and uid=16782132 and uid>10000 and uid<1000000 and uid in(16791444,16782132,16807195) and (uid=16782132 and sex=0) or (uid=1304049 and sex=1)

期望的结果:

array=(
'0'=>personname like '%南京%',
'1'=>and uid=16782132,
'2'=>and uid>10000,
'3'=>and uid<1000000,
'4'=>and uid in(16791444,16782132,16807195),
'5'=>and (uid=16782132 and sex=0),
'6'=>or (uid=1304049 and sex=1)
)
...全文
193 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
vgy12304 2012-10-19
  • 打赏
  • 举报
回复
楼上的正解,非常感谢
xuzuning 2012-10-18
  • 打赏
  • 举报
回复
只用简单的正则估计是做不到的
你可以这样写
$s =<<< TXT
select * from tjw_person where personname like '%南京%' and uid=16782132 and uid>10000 and uid<1000000 and uid in(16791444,16782132,16807195) and (uid=16782132 and sex=0) or (uid=1304049 and sex=1)
TXT;

$t = preg_split('/(\bwhere\b|\bgroup\b|\border\b|\blimit\b)/i', $s, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);

$t = preg_split('/(\band\b|\bor\b)/i', $t[2], -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
for($i=0; $i<count($t); $i++) {
$v = $t[$i];
if(in_array($v, array('and', 'or'))) {
$v .= $t[++$i];
if(strstr($v, '(')) while(!strstr($v, ')')) $v .= $t[++$i];
}
$r[] = $v;
}
print_r($r);
Array
(
[0] => personname like '%南京%'
[1] => and uid=16782132
[2] => and uid>10000
[3] => and uid<1000000
[4] => and uid in(16791444,16782132,16807195)
[5] => and (uid=16782132 and sex=0)
[6] => or (uid=1304049 and sex=1)
)

vgy12304 2012-10-18
  • 打赏
  • 举报
回复
附上取where所有条件的正则
if(stripos($sql,'order')!==false){
preg_match("/where\s+(.*)\s*order/",$sql,$matchs);
}elseif(stripos($sql,'group')!==false){
preg_match("/where\s+(.*)\s*group/",$sql,$matchs);
}elseif(stripos($sql,'limit')!==false){
preg_match("/where\s+(.*)\s*limit/",$sql,$matchs);
}else{
preg_match("/where\s+(.*)\s*/",$sql,$matchs);
}
$where=trim($matchs[1]);

21,886

社区成员

发帖
与我相关
我的任务
社区描述
从PHP安装配置,PHP入门,PHP基础到PHP应用
社区管理员
  • 基础编程社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧