The content of this article is about how to extract numbers from strings in PHP? Summary of the method of extracting numbers in strings in PHP (with code), which has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
PHP extracts the first group of numbers in a string
<?php $str='acc123nmnm4545'; if(preg_match('/\d+/',$str,$arr)){ echo $arr[0]; } ?>
Other methods for PHP to extract numbers in a string
The first method is to use regular expressions Formula:
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 ''; }
The second method, use the in_array method:
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; }
The third method, use the is_numeric function:
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; }
For example:
//截取字符串中的数字2 $str ='Q币2个'; $result=''; for($i=0;$i<strlen($str);$i++){ if(is_numeric($str[$i])){ $result.=$str[$i]; } } print_r($result);die; //输出结果 2
Related recommendations:
PHP method to extract numbers in a string
php extracts numbers in a string Digital Tutorial
The above is the detailed content of How to extract numbers from string in php? Summary of methods for extracting numbers from strings in PHP (with code). For more information, please follow other related articles on the PHP Chinese website!