This article, will discuss multiple ways to remove all characters except numbers from a string in PHP.
Table Of Contents
Background
There are scenarios in PHP development where you might need to extract only the numeric part of a string, discarding all other characters. This is often required in data processing, form validation, or when dealing with numerical data embedded in text.
For example, if you have the following string:
$originalString = "Phone: 123-456-7890";
Your goal is to keep only the numbers, resulting in:
"1234567890"
Let’s explore some methods to achieve this.
Solution 1: Using preg_replace()
The preg_replace() function performs a regular expression search and replace. You can use it to replace all non-numeric characters with an empty string, effectively keeping only the numbers.
Frequently Asked:
- Remove a string between two characters in PHP
- Remove Line Breaks from a String in PHP
- Remove a String after a Space in PHP
- Trim a String by length in PHP
Let’s see the complete example,
<?php $originalString = "Phone: 123-456-7890"; // Remove all non-numeric characters $numericString = preg_replace('/[^0-9]/', '', $originalString); echo $numericString; ?>
Output
1234567890
In this code:
– The regular expression /[^0-9]/ matches any character that is not a digit.
– preg_replace(‘/[^0-9]/’, ”, $originalString) replaces every non-digit character with an empty string.
– The resulting string contains only the numbers from the original string.
Solution 2: Using filter_var()
Another approach is to use the filter_var() function with the FILTER_SANITIZE_NUMBER_INT filter. This filter removes all characters except digits and plus/minus signs.
Let’s see the complete example,
<?php $originalString = "Phone: 123-456-7890"; // Remove all characters except numbers $numericString = filter_var($originalString, FILTER_SANITIZE_NUMBER_INT); echo $numericString; ?>
Output
123-456-7890
In this code:
– filter_var($originalString, FILTER_SANITIZE_NUMBER_INT) applies the FILTER_SANITIZE_NUMBER_INT filter to $originalString.
– This method keeps digits and removes all other characters, including punctuation and spaces.
Summary
To remove all characters except numbers from a string in PHP, both preg_replace() with an appropriate regular expression and filter_var() with the FILTER_SANITIZE_NUMBER_INT filter are effective. The choice between them depends on your specific requirements and whether you need to keep certain non-numeric characters like plus or minus signs.