Home  >  Article  >  Backend Development  >  Tutorial on extracting numbers from string in php

Tutorial on extracting numbers from string in php

小云云
小云云Original
2017-11-17 17:40:584144browse

Strings are what we programmers must come into contact with legal persons. Sometimes we need to extract all the numbers from a string at work. In fact, there are quite a lot of research on this method. How to use PHP to extract the numbers in a string? We have made a small summary of the functions of number extraction and would like to share it with you. The three methods are summarized as follows:

The first method uses regular expressions:

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 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=&#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;
}

The above three methods are all methods of extracting numbers in strings using PHP. You can Choose the one that suits you best.

Related recommendations:

Solution to the problem of Chinese garbled characters when php intercepts strings

php function strtr to convert specific characters in a string ()

php intercepts the function substr() that returns a string

The above is the detailed content of Tutorial on extracting numbers from string in php. 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