Reputation: 329
Thank you for taking time to read my question. I'm trying to filter out non-numeric values from a variable in php. This is what I've tried:
$output="76gg7hg67ku6";
preg_replace('/\d/', $output, $level)
echo $level;
Preg replace should set $level to 767676, but when I echo level it has nothing in it. Your help is greatly appreciated.
Upvotes: 0
Views: 296
Reputation: 30995
You have to use \D
to replace the non digits
$re = "/\\D/";
$str = "76gg7hg67ku6";
$subst = "";
$result = preg_replace($re, $subst, $str);
Just fyi:
\D match any character that's not a digit [^0-9]
\d match a digit [0-9]
Upvotes: 1
Reputation: 880
In addition to the preg_replace
fixes others are posting, it's worth mentioning that it might be easier to just use filter_var
:
$output = "76gg7hg67ku6";
$output = filter_var($output, FILTER_SANITIZE_NUMBER_INT);
Working example: http://3v4l.org/AEPIh
Upvotes: 3
Reputation: 3709
You can do this like this:
preg_replace("/[^0-9]/","","76gg7hg67ku6");
Upvotes: 2
Reputation: 59691
This should work for you:
$input = "76gg7hg67ku6";
echo preg_replace("/[^\d]/", "", $input);
Output:
767676
regex:
For more information about preg_replace()
see the manual: http://php.net/manual/en/function.preg-replace.php
And a quote from there:
mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
Upvotes: 2