感谢您花时间阅读我的问题。我试图从php中的变量中过滤掉非数字值。这就是我尝试过的:
$output="76gg7hg67ku6";
preg_replace('/\d/', $output, $level)
echo $level;
Preg replace应该将$ level设置为767676,但是当我回显级别时它没有任何内容。非常感谢您的帮助。
答案 0 :(得分:3)
除了其他人发布的preg_replace
修正补丁之外,值得一提的是,使用filter_var
可能更容易:
$output = "76gg7hg67ku6";
$output = filter_var($output, FILTER_SANITIZE_NUMBER_INT);
答案 1 :(得分:2)
这应该适合你:
$input = "76gg7hg67ku6";
echo preg_replace("/[^\d]/", "", $input);
输出:
767676
正则表达式:
有关preg_replace()
的详情,请参阅手册:http://php.net/manual/en/function.preg-replace.php
从那里引用:
混合preg_replace(混合$ pattern,混合$替换,混合$ subject [,int $ limit = -1 [,int& $ count]])
答案 2 :(得分:1)
你可以这样做:
preg_replace("/[^0-9]/","","76gg7hg67ku6");
答案 3 :(得分:1)
您必须使用\D
替换非数字
$re = "/\\D/";
$str = "76gg7hg67ku6";
$subst = "";
$result = preg_replace($re, $subst, $str);
只是fyi:
\D match any character that's not a digit [^0-9]
\d match a digit [0-9]
<强> Working demo 强>