dongzhong7443 2013-04-17 18:04
浏览 542
已采纳

检查字符串是否为整数(包括负数)PHP

The function below checks if a string is an integer meaning it should only contain digits. But it does not check if number is negative (negative numbers should return true as well since they are integers).

function validateInteger($value)
{
   //need is_numeric to avoid $value = true returns true with preg_match
   return is_numeric($value) && preg_match('/^\d+$/', $value);
}

I ran tests and got results:

'12.5'      => FALSE 
12.5        => FALSE 
'a125'      => FALSE 
'125a'      => FALSE 
'1a2.5'     => FALSE 
125         => TRUE 
'abc'       => FALSE 
false       => FALSE 
true        => FALSE 
'false'     => FALSE 
'true'      => FALSE 
null        => FALSE 
'null'      => FALSE 
'1231'      => TRUE 
-1231       => FALSE (SHOULD RETURN TRUE)
'-1231'     => FALSE (SHOULD RETURN TRUE)

I dont want to use itnval() < 0. I would prefer regular expression to check for negative numbers as well.

Thanks

EDIT:

I also have a function validateFloat that returns true if a given number is floating number meaning it can contain only digits and a dot. I need to apply same logic to this as well so that it returns true for negative floating numbers

  • 写回答

2条回答 默认 最新

  • douke9545 2013-04-17 18:12
    关注

    just use is_numeric(abs($val))

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记