0

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.

3
  • 1
    $level = preg_replace('/[^\d]/', '', $output); maybe? Commented Mar 17, 2015 at 17:28
  • please see the preg_replace doc. Commented Mar 17, 2015 at 17:28
  • You don't show us $level, but you would be replacing instances of \d in $level with $output. From the docs: preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] ) Commented Mar 17, 2015 at 17:29

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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 ]] )

1 Comment

[^\d] is more simply expressed as \D.
2

You can do this like this:

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.