How Do I Take Out Only Numbers From A PHP String?

How Do I Take Out Only Numbers From A PHP String?

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

Stefan Bogdanescu

Founder & Senior Architect

Extracting Pure Integers from PHP Strings: A Practical Guide

When working with data ingestion or parsing user input, you often encounter strings that contain non-numeric characters mixed with numbers. The goal is frequently to isolate specific digits and reconstruct them into a usable integer variable. In PHP, this process requires moving beyond simple type casting because intval() or (int) casts stop at the first non-numeric character they encounter.

Consider a scenario where you have the string $string = "Hello! 123 How Are You? 456";. If your requirement is to extract only the digits and combine them into a single integer like 123456, standard casting will fail immediately. The expression (int)"Hello! 123" results in 0 because the cast stops at the letter "H". To achieve the desired outcome of concatenating all numeric sequences, you must first isolate the digits and then join them.

The most robust approach involves using a Regular Expression (Regex) with the /u modifier or simply leveraging PHP's built-in filtering capabilities. A common pattern is to use preg_match_all() with a specific character class that matches only digits: [0-9]. This function captures all matching substrings in an array, which you can then implode into a single string before casting to an integer.

$string = "Hello! 123 How Are You? 456";
$numbers = [];

// Extract all sequences of digits
preg_match_all('/\d+/', $string, $matches);

// Combine the extracted numbers into a single string
$combinedString = implode('', $matches[0]);

// Cast to integer
$int = (int)$combinedString; // Result: 123456

However, a more concise and often preferred method for modern PHP versions is using preg_replace() to strip everything that isn't a digit, followed by an explicit cast. This removes all letters, punctuation, and whitespace in one pass, leaving only the digits.

$string = "Hello! 123 How Are You? 456";
$int = (int) preg_replace('/[^0-9]/', '', $string);
// Result: 123456

This second example demonstrates why understanding the regex character class is crucial. The pattern /[^0-9]/ defines a "negated character class," meaning it matches any character that is not a digit between 0 and 9. Replacing these with an empty string effectively filters the noise.

Handling Commas and Delimiters

Real-world data often includes formatting characters like commas, which are significant in decimal notation but invalid for standard integer types. Take the string $string = "12,456";. If you attempt (int)"12,456", PHP interprets this as 0 because the comma is not a valid digit character.

To convert "12,456" into the integer 12456, you must remove the comma before casting. The regex approach remains consistent here; you simply ensure your negative character class excludes commas.

$string = "12,456";
$num = (int) preg_replace('/[^0-9]/', '', $string);
// Result: 12456

It is important to note that this logic assumes you want to treat the comma purely as noise. If your input represents currency or requires decimal precision, stripping non-digits entirely would be a destructive operation that loses data integrity. Always verify whether the source string implies a specific unit (like dollars) where the numeric part alone might not suffice for downstream calculations.

Performance and Readability Considerations

While preg_replace is concise, it involves regex compilation overhead if called repeatedly within tight loops. For high-performance applications processing millions of rows, you might consider using str_replace with a custom delimiter if the non-numeric characters are known in advance (e.g., removing only spaces and commas). However, for general string parsing where the noise is unpredictable, regex offers the flexibility to handle complex patterns without bloating your logic.

Another pitfall to avoid is relying solely on intval() without validation. If the string contains leading zeros (e.g., "007"), PHP's default behavior treats them as octal in some contexts or simply truncates them depending on the version and flags used. Explicitly using (int) after cleaning ensures a base-10 interpretation of the resulting digit sequence.

For developers working within the Laravel ecosystem, utility services like Str provide helper methods that wrap these regex operations, making the code more readable while abstracting the underlying complexity. When dealing with massive datasets or complex parsing requirements, leveraging established libraries can save development time and reduce the risk of subtle bugs related to edge cases in string manipulation.

Our network