Skip to content
PHP Logo

How can regular expressions be used in PHP to validate decimal or integer numbers with comma or dot separators?

Regular expressions can be used in PHP to validate decimal or integer numbers with comma or dot separators by defining a pattern that matches the desired format. The pattern should allow for an optional negative sign at the beginning, followed by digits for the integer part, and optionally a decimal point or comma with digits for the fractional part. By using the preg_match function in PHP, we can check if a given input string matches the defined pattern, indicating whether it is a valid decimal or integer number with the specified separators.

php
$input = "123.45";
$pattern = "/^-?\d+(?:[\.,]\d+)?$/";

if (preg_match($pattern, $input)) {
    echo "Valid number format";
} else {
    echo "Invalid number format";
}