how to check if PHP variable contains non-numbers?

前端 未结 10 2079
执笔经年
执笔经年 2021-02-18 22:09

I just want to know the method to check a PHP variable for any non-numbers and if it also detects spaces between characters? Need to make sure nothing weird gets put into my for

10条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-18 22:18

    This worked out to be ~30% faster than preg_match for my test cases, while still letting you match any characters you want:

    if( $a !== '' && trim($a, ' 1234567890.,') === '' ){
       print("The variable contains only digits, decimal separators and spaces");
    }
    
    

    This simply removes all characters supplied from the string. If the result is an empty string, you know it only contained those characters.

提交回复
热议问题