本文操作环境:windows7系统、php8版,dell g3电脑
php提取字符串中的数字
php提取字符串中的第一组数字
<?php $str='acc123nmnm4545'; if(preg_match('/\d+/',$str,$arr)){ echo $arr[0]; }?>
php提取字符串中的数字的其它方法
第一种方法,使用正则表达式:
function findnum($str=''){$str=trim($str);if(empty($str)){return '';}$reg='/(\d{3}(\.\d+)?)/is';//匹配数字的正则表达式preg_match_all($reg,$str,$result);if(is_array($result)&&!empty($result)&&!empty($result[1])&&!empty($result[1][0])){return $result[1][0];}return '';}
第二种方法,使用in_array方法:
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;}
第三种方法,使用is_numeric函数:
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;}
【推荐:php视频教程】
以上就是php怎么实现只获取数字的详细内容。
