douchuntang2827 2014-03-19 20:34
浏览 111
已采纳

preg_match函数无法正常工作

I am trying to filter all the letters and special characters, and only allow numbers. But whenever I pass a 0 as a variable, it is returning me false.

 $string = 0;
   if(preg_replace('/[^0-9]/', '', $string) == true){
      echo 'True';
   }else{
      echo 'False';
   }
  • 写回答

1条回答 默认 最新

  • dshdsh2016 2014-03-19 20:53
    关注

    preg_replace

    If matches are found, the new subject will be returned, otherwise subject will be returned unchanged or NULL if an error occurred.

    When you check preg_replace('/[^0-9]/', '', $string) == true it is checking the string '0' after it has been stripped of all non-numeric characters (still '0') and seeing if it evaluates to TRUE. The string '0' and the int 0 both evaluate to FALSE. I.e '0' == FALSE && 0 == FALSE. This is why your condition is returning FALSE since '0' == FALSE.

    You can change your condition to this instead: preg_replace('/[^0-9]/', '', $string) != ''

    Now you will be checking to see if your string is empty after filtering out all non-numeric characters I.e if your string contained only non-numeric characters it would return FALSE.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部