PHP只保留数字如何实现?

2020-08-12 21:06:31

PHP只保留数字如何实现?

1、使用正则匹配出所有的数字并提取出来,或替换掉不是数字的字符;

<?php    $str='acc123nmnm4545';    if(preg_match('/d+/',$str,$arr)){       echo $arr[0];    }?>

2、把字符串拆分为数组,并历遍数组判断每个字符是否为数字,如果是提取出来即可。

function findNum($str=''){$str=trim($str);if(empty($str)){return '';}$temp=array('1','2','3','4','5','6','7','8','9','0');$result='';for($i=0;$i<strlen($str);$i++){if(in_array($str[$i],$temp)){$result.=$str[$i];}}return $result;}
function findNum($str=''){$str=trim($str);if(empty($str)){return '';}$result='';for($i=0;$i<strlen($str);$i++){if(is_numeric($str[$i])){$result.=$str[$i];}}return $result;}
相关文章 大家在看