Home  >  Article  >  Backend Development  >  Summary of methods for extracting numbers from strings in PHP (code)

Summary of methods for extracting numbers from strings in PHP (code)

不言
不言Original
2018-08-03 13:51:415710browse

This article introduces to you a summary (code) of the method of extracting numbers from strings in PHP. It 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=&#39;acc123nmnm4545&#39;;
    if(preg_match(&#39;/\d+/&#39;,$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=&#39;&#39;){
$str=trim($str);
if(empty($str)){return &#39;&#39;;}
$reg=&#39;/(\d{3}(\.\d+)?)/is&#39;;//匹配数字的正则表达式
preg_match_all($reg,$str,$result);
if(is_array($result)&&!empty($result)&&!empty($result[1])&&!empty($result[1][0])){
return $result[1][0];
}
return &#39;&#39;;
}

The second method, use the in_array method:

function findNum($str=&#39;&#39;){
$str=trim($str);
if(empty($str)){return &#39;&#39;;}
$temp=array(&#39;1&#39;,&#39;2&#39;,&#39;3&#39;,&#39;4&#39;,&#39;5&#39;,&#39;6&#39;,&#39;7&#39;,&#39;8&#39;,&#39;9&#39;,&#39;0&#39;);
$result=&#39;&#39;;
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=&#39;&#39;){
$str=trim($str);
if(empty($str)){return &#39;&#39;;}
$result=&#39;&#39;;
for($i=0;$i<strlen($str);$i++){
if(is_numeric($str[$i])){
$result.=$str[$i];
}
}
return $result;
}

For example:

//截取字符串中的数字2
    $str =&#39;Q币2个&#39;;
    $result=&#39;&#39;;
    for($i=0;$i<strlen($str);$i++){
        if(is_numeric($str[$i])){
            $result.=$str[$i];
        }
    }
    print_r($result);die;
    //输出结果 2

Recommended related articles:

How to process images (code) when php and ajax are combined

php中_get Method and _set method access method example code

The above is the detailed content of Summary of methods for extracting numbers from strings in PHP (code). For more information, please follow other related articles on the PHP Chinese website!

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