In this tutorial we will see How To Remove Everything from String Except Numbers Using PHP. Php preg_replace() function with regular expression and filter_var() function with php FILTER_SANITIZE_NUMBER_INT filter can be used for this.
Table of Contents
preg_replace() Function
preg_replace() Function is a built-in php function which is used to replace a pattern in string with the replacement or substring.
Regular expression
Regular expression is a sequence of characters that specifies a search pattern. Regular expression is used with php preg_replace function to replace the search pattern.
Example of preg_replace() Function with regex is given below.
<?php
$number = '12345abcd!@#$%+1';
$number = preg_replace("/[^0-9]/","",$number);
echo $number;
?>
Output
123451 will be the output. Everything is replaced except numbers.
Second example of preg_replace() function with \D Metacharacter is given below.
<?php
$number = '12345abcd!@#$%+1';
$number = preg_replace('/\D/', '', $number);
echo $number;
?>
Output
123451 will be the output.
filter_var() Function
filter_var() Function filters or replaces a string or variable with the specified filter. FILTER_SANITIZE_NUMBER_INT filter is used with filter_var() function to replace all types of characters and alphabets from string but numbers.
FILTER_SANITIZE_NUMBER_INT Filter
PHP FILTER_SANITIZE_NUMBER_INT Filter is a filter which removes all characters and alphabets from a string except numbers and . + -.
Take a look at the example given below.
<?php
$number = '12345abcd!@#$%+1';
$number = filter_var($number, FILTER_SANITIZE_NUMBER_INT);
echo $number;
?>
Output
12345+1 will be the output. Due to FILTER_SANITIZE_NUMBER_INT, the + sign is not replaced.
This should be used when you are dealing with phone numbers since they contain + and - signs.
More PHP Remove Tutorials:
Remove Dashes from StringRemove Spaces from String
Remove Underscore from String
Remove Single Quotes from String
Remove Double Quotes from String
Remove Backslash from String
Remove Forward Slash from String
Remove Last Character from String
Remove First Character from String