PHP regular expression - filter number only

PHP regular expression - filter number only

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Validating and Cleaning Numeric Input in PHP

When handling user input for financial calculations or data processing, assuming a string is a valid number immediately after retrieval is a recipe for runtime errors. A common scenario involves fields where users might input timestamps like 15:00 instead of pure decimals, or accidentally include currency symbols and whitespace. The goal isn't just to check if a value exists; it's to sanitize the data so functions like number_format() operate on clean integers or floats without triggering warnings or unexpected output.

Regular expressions are the standard tool for this validation and extraction task in PHP. However, relying solely on preg_match to filter characters often leads to fragile code because that function returns a boolean indicating whether a match occurred, not the cleaned string itself. If you attempt to pass the result of preg_match directly into number_format(), you will encounter type errors unless you extract the matched group or manually strip non-numeric characters using implode on an array of matches.

To solve this efficiently, you should use a capturing group within your regex pattern and then access that specific match from the result array. Consider a pattern designed to accept an optional minus sign, followed by digits with optional decimal points:

$pattern = '/^-?\d+(\.\d+)?$/';
$string = '15:00';

if (preg_match($pattern, $string, $matches)) {
    // $matches[0] contains the full match
    $cleanNumber = $matches[0]; 
    echo number_format($cleanNumber);
} else {
    // Handle invalid input
    throw new InvalidArgumentException("Invalid number format detected.");
}

In this approach, the regex ^-?\d+(\.\d+)?$ ensures that only digits and a single decimal point are allowed. The colon in 15:00 fails this check because it breaks the contiguous sequence of digits required by \d. If you need to extract numbers from a messier string where you want to ignore the non-numeric parts rather than reject the whole input, you might use a pattern that captures all sequences of digits. For example, /[-]?\d+\.?\d*/ could extract 15 and 00 separately if they are separated by delimiters, but it would likely fail to parse 15:00 as a single decimal number because the regex engine stops matching at the colon.

A critical pitfall in this workflow is ignoring the return value of preg_match. Many developers mistakenly think they can pass the associative array returned by the function directly into math functions. PHP's arithmetic and formatting functions expect scalars, not arrays. You must explicitly reference $matches[0] to get the matched string. Another common mistake is using preg_replace to strip characters blindly without validating the result. For instance, removing everything except digits with /[^0-9]/ might leave behind a decimal point in an invalid position or handle scientific notation incorrectly depending on your specific use case.

If you are building a larger application where input validation happens frequently, consider leveraging Laravel's built-in validation helpers to keep your code readable and safe. The LaravelCompany ecosystem often emphasizes robust form handling; while their documentation covers many topics, the core principle remains that regular expressions should be used for structural validation, not as a substitute for proper data type casting. In a Laravel controller, you might cast the input to float after ensuring it passes regex validation, rather than trying to force the string through number_format before conversion.

Ultimately, the choice between validating first and cleaning later depends on your business logic. If the input 15:00 represents a specific time and must be rejected as a currency value, a strict regex is necessary. If it represents a price where the colon was a typo, you might need to decide whether to treat it as an error or sanitize it by removing the colon entirely. However, blindly removing characters with str_replace is often less reliable than defining a strict pattern that only accepts valid numeric representations in the first place.

Our network