PHP - remove all non-numeric characters from a string
When you need to strip non-numeric characters from a string in PHP, the immediate instinct is often to reach for a regular expression. For the specific use case of extracting standalone numbersâlike turning "12 months" into 12 or "Every 6 months" into 6âregex is not just an option; it is the most robust and readable solution available in the core language.
While there are older, more convoluted approaches that involve looping through characters and concatenating digits, those methods fail to handle whitespace correctly without extra logic and generally offer poor performance compared to built-in regex engines. The preg_replace function provides a direct way to isolate the numeric content you care about while discarding units of time, currency symbols, or descriptive text.
The Regex Pattern Strategy
To remove everything that isn't a number, we need a pattern that targets any character sequence containing digits and replaces it with just those digits. A common approach is to use a negative lookahead or a pattern that captures digits specifically.
However, the most straightforward implementation for this specific requirementâextracting the numeric value regardless of surrounding textâis to match one or more digits and replace them with themselves, while ensuring we only capture complete numbers. If your goal is simply to leave the numbers intact and delete everything else, including whitespace attached to them, a simple pattern works well:
$string = '12 months Every 6 months 1M';
// Matches one or more digits and replaces the whole string with just those digits
// Note: This approach depends on how you want to handle multiple numbers.
$result = preg_replace('/\d+/', '', $string);
// Result: " months Every months M" (This is NOT what we want)
The above example highlights a common pitfall. Simply removing non-digits often leaves behind whitespace that was originally adjacent to the numbers, resulting in empty spaces or unwanted formatting artifacts. To truly isolate the number and discard the unit, you must match the number and the surrounding text as a single unit if your goal is extraction, or use a capturing group to keep only the digits.
A more precise strategy for extracting standalone numbers from a mixed string is to use a pattern that matches one or more digits while ignoring what comes before or after them. If you want to retain only the numbers and discard everything else in the final output (as implied by your examples), you should match the entire string's numeric components and reconstruct the string with only those components:
$string = '12 months Every 6 months 1M';
// This pattern matches any sequence of digits.
// We use a callback or a simpler replacement logic depending on needs.
// However, for pure extraction where we want ONLY the numbers concatenated:
$numbersOnly = preg_replace('/[^0-9]/', '', $string);
echo $numbersOnly; // Outputs: 1261
Wait, that output (1261) concatenates all digits together. If your requirement is to keep the numbers distinct but remove their units (e.g., keeping 12 separate from 6), you must ensure the regex respects word boundaries or whitespace.
If the goal is strictly to extract the numeric values while preserving their order and ignoring text, a global match approach is better:
$string = '12 months Every 6 months 1M';
// Extract all digit sequences and join them if you want a single string of numbers
$numbers = preg_replace('/\D/', '', $string);
// Output: "1261"
If your requirement is to return a string that contains only the numbers found in the original text, stripped of all units and labels, the simplest path is removing every character that is not a digit:
$string = '12 months Every 6 months 1M';
$cleaned = preg_replace('/\D/', '', $string);
// Result: "1261"
This approach assumes you want to collapse all numbers into one continuous string. If you need to preserve the count of numbers (e.g., an array of ['12', '6', '1']), you would use preg_match_all instead.
Performance and Readability Considerations
Using preg_replace with the \D pattern is significantly faster than iterating over a string in a loop to check character codes (ctype_digit). The PCRE engine is highly optimized for this type of character class matching, making it the standard tool for text sanitization tasks in PHP.
However, be mindful of edge cases involving floating-point numbers or scientific notation if your source data includes them. The \D pattern treats dots and 'e'/'E' as non-numeric characters unless explicitly included in the allowed set. If your string contains 12.5, removing non-digits will turn it into 125. Always verify whether decimals are part of your expected input before applying a blanket "remove non-digit" rule.
In production environments where data consistency is critical, ensure that you handle empty strings and null values explicitly before passing them to regex functions to avoid unexpected warnings or type errors. While PHP's regex engine handles these gracefully in most cases, explicit checks improve code robustness.
