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

Tutorial on extracting numbers from string in php

小云云
Release: 2023-03-17 15:50:02
Original
4212 people have browsed it

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 '';
}
Copy after login

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;
}
Copy after login

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;
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template