做一个分页的。
想把形如:
SELECT u.id,u.name FROM user as u ORDER BY u.id DESC LIMIT 0 10
SELECT u.id,u.name FROM user as u WHERE u.id=12 ORDER BY u.id DESC
替换成
SELECT COUNT(*) FROM user as u ORDER BY u.id DESC LIMIT 1
SELECT COUNT(*) FROM user as u WHERE u.id=12 ORDER BY u.id DESC LIMIT 1
也就是形式如
SELECT xxxxx FROM ***** WHERE ***** ORDER BY **** LIMIT XXXXX
SELECT xxxxx FROM ***** WHERE ***** ORDER BY ****
其中 XXXXX 部分进行替换。
PHP 怎么写正则。。。
------解决方案--------------------
- PHP code
$str="SELECT u.id,u.name FROM user as u WHERE u.id=12 ORDER BY u.id DESC limit 10";echo preg_replace("/^(select ).+? (from .+?)(limit (\d{1,}(\,\d{1,})?))?$/i","\\1 count(*) \\2 limit 1;",$str);
------解决方案--------------------
<?php
$str="SELECT u.id,u.name FROM user as u WHERE u.id=12 ORDER BY u.id DESC limit 1,10";
echo preg_replace("/^(select ).+ (from.+?)( limit [0-9\,]+){0,1}$/i","\\1 count(*) \\2 limit 1",$str);
echo "<br />";
$str="SELECT u.id,u.name FROM user as u WHERE u.id=12 ORDER BY u.id DESC";
echo preg_replace("/^(select ).+ (from.+?)( limit [0-9\,]+){0,1}$/i","\\1 count(*) \\2 limit 1",$str);
?>