php验证整数或小数二位的正则

85 阅读1分钟

在工作环境中,我们会遇到这样的场景,就是说提交的数据,需要判断是整数或小数还是字符串,所以,我们一开始使用的intval,这个如果遇到字符串直接就转成0,不符合需求,所以修改成正则来修改。废话不多说,看下面代码

public function index(){

 $accountPrice = '123.3';
// $accountPrice = 1112.;
// $accountPrice = 2324.1;
// $accountPrice = 2324.15;
// $accountPrice = 2324.157;//wrong
// $accountPrice = 0.57;


        if (preg_match('/^[0-9]+(.[0-9]{1,2})?$/', $accountPrice)) {
            echo $accountPrice;
        }else{
            echo 'NO';
        }


    }