PHP Validation Numbers Only From

How to check for number values only and block or convert letter strings to integers.

Question: How to validate number values to and block all letters and symbol in a form.

Answer: You can check the value or convert the value to an integer (number).

1) Check a value using is_int() to finds whether the given variable is an integer

echo "Pass test";
echo "Please use only numbers";

2) Note: To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric().

echo "Pass test";
echo "Please use only numbers";

3) Convert the value to an integer (number) using settype.

$foo = "5bar"; // string
$bar = true; // boolean

settype($foo, “integer”); // $foo is now 5 (integer)
settype($bar, “string”); // $bar is now “1” (string)

or you can use int to do the trick.

$int=593; // $int is a integer
$int.=""; // $int is now a string

Tagged : / / / / / / / /

7 thoughts on “PHP Validation Numbers Only From

  1. If you want to convert ‘(555) 555-5555’ to ‘5555555555’, for example, use this:

    $phone_number_as_string = '(555) 555-5555';
    // Outputs '(555) 555-5555'

    $phone_number_as_integer = preg_replace("/[^0-9]/", "", $phone_number_as_string);
    // Outputs 5555555555

    If you want to reformat your phone number into a different string, as ‘555-555-5555’, for example, use this:

    // Regular Expression
    $phone_number_as_integer_template = '/([0-9]{3})([0-9]{3})([0-9]{4})/';

    // Split phone number into array of 3 parts (phone_number_fields) 1/2/3 ('0' is all matches)
    preg_match($phone_number_as_integer_template, $phone_number_as_integer, $phone_number_fields);

    // Use these three parts to re-construct the phone number (separated by dashes)
    $phone_number_formatted = $phone_number_fields[1] . '-' . $phone_number_fields[2] . '-' . $phone_number_fields[3];

    print $phone_number_formatted;
    // Outputs '555-555-5555'

  2. To blindly block non-numeric characters just cast the input as an int.

    $input = (int) $_GET[‘int’];

    also, +1 for ctype_digit().

Leave a Reply

Your email address will not be published. Required fields are marked *