Grant
Grant

Reputation: 329

Trying to filter out non-numeric values with regex in php

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

Answers (4)

Federico Piazza
Federico Piazza

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]

Working demo

enter image description here

Upvotes: 1

JoeCoder
JoeCoder

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

Marc
Marc

Reputation: 3709

You can do this like this:

preg_replace("/[^0-9]/","","76gg7hg67ku6");

Upvotes: 2

Rizier123
Rizier123

Reputation: 59691

This should work for you:

$input = "76gg7hg67ku6";
echo preg_replace("/[^\d]/", "", $input);

Output:

767676

regex:

  • [^\d] match a single character not present in the list
    • \d match a digit [0-9]

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

Related Questions