有SQL:
select a,b,c,d from `tab` where a=1 and b=1 order by d desc

select a,b,c,d from `tab` order by d desc

select a,b,c,d from `tab`如何通过正则替换后变成select count(1) from `tab` where a=1 and b=1

select count(1) from `tab`红色部分是不定的最好是一句正则就能完成
下面是life169给出的答案(未删除order之后的字符)
$str = "select a,b,c,d from `tab` where a=1 and b=1 order by d desc";
$str = "select a,b,c,d from `tab` order by d desc";
$str = "select a,b,c,d from `tab`";
$str = "select * from `tab`";
$f = array();
$t = array();
$str = str_replace('`','',$str);
preg_match('/select\s+(.*?)\s+from/i',$str,$match);
$match[1] == '*' ? $f[] = "/\\".$match[1]."/i" : $f[] = "/".$match[1]."/i" ;
$t[] = 'count(1)';
if(preg_match('/by\s+(\w+)\s+(asc|desc)/i',$str,$match)){
  $f[] = "/ ".$match[1]." /i" ;
  $f[] = "/".$match[2]."/i" ;
  $t[] = ' 主键 ';
  $t[] = 'asc';
}
$str = preg_replace($f,$t,$str);
echo $str ;

解决方案 »

  1.   

    <?php
    $str = 'select a,b,c,d from `tab` where a=1 and b=1 order by d desc';
    $str = preg_replace('/select (.*) from/i', 'select count(1) from', $str);
    echo $str;
      

  2.   

    $str = "select a,b,c,d from `tab` where a=1 and b=1 order by d desc";
    $pattern = array("/select(.*)from/","/order by(.*)/");
    $replacement = array("select count(1) from ","");
    $str = preg_replace($pattern,$replacement,$str);
    echo $str;
      

  3.   


    $str = 'select a,b,c,d from `tab` where a=1 and b=1 order by d desc';
    $f = array('/select.*from/is','/order.*$/is');
    $t = array('select count(1) from','');
    $str = preg_replace($f, $t, $str);
    echo $str ;