Filter out numbers in a string in php

$str = "e3r4t5";
$str_numbers_only = preg_replace("/[^\d]/", "", $str);

// $number = (int) $str;

Sorry for joining the bandwagon late, rather than using Regex, I would suggest you use PHP's built in functions, which may be faster than Regex.

filter_var

flags for the filters

e.g. to get just numbers from the given string

<?php
$a = '!a-b.c3@j+dk9.0$3e8`~]\]2';
$number = str_replace(['+', '-'], '', filter_var($a, FILTER_SANITIZE_NUMBER_INT));
// Output is 390382
?>

To adhere to more strict standards for your question, I have updated my answer to give a better result.

I have added str_replace, as FILTER_SANITIZE_NUMBER_FLOAT or INT flag will not strip + and - chars from the string, because they are part of PHP's exception rule.

Though it has made the filter bit long, but it's now has less chance of failing or giving you unexpected results, and this will be faster than REGEX.

Edit:

1: Realized that with FILTER_SANITIZE_NUMBER_FLOAT, PHP won't strip these characters optionally .,eE, hence to get just pure numbers kindly use FILTER_SANITIZE_NUMBER_INT

2: If you have a PHP version less than 5.4, then kindly use array('+', '-') instead of the short array syntax ['+', '-'].


You can use a regular expression to remove any character that is not a digit:

preg_replace('/\D/', '', $str)

Here the pattern \D describes any character that is not a digit (complement to \d).

Tags:

Php