Home >Backend Development >PHP Tutorial > 新手php正则取数字

新手php正则取数字

WBOY
WBOYOriginal
2016-06-13 13:43:17709browse

新手求助php正则取数字

$x="123xadg2hj5ed";

我想取出$x里所有的数字其它字符不要,感谢帮助。

$str="5555555ddd";
ereg("[0-9]",$str,$a);
echo $a;
我这么写有不行啊。

------解决方案--------------------
preg_match("/[0-9]+/",$str,$a);
------解决方案--------------------
$str = "5555555ddd"; 
ereg("[0-9]+",$str,$a); 
print_r($a);//Array ( [0] => 5555555 ) 


$str = "123xadg2hj5ed"; 
preg_match_all("/[0-9]+/",$str,$a); 
print_r($a);//Array ( [0] => Array ( [0] => 123 [1] => 2 [2] => 5 ) )
------解决方案--------------------

PHP code
<?php $x="123xadg2hj5ed";
echo preg_replace('/\D+/','',$x);//数字全部连起来
preg_match_all('/\d+/',$x,$r);//数字要分开
print_r($r[0]);
?> <div class="clear">
                 
              
              
        
            </div>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn