DEV Community

leichengde
leichengde

Posted on

How to extract the first set of numbers in a string using PHP

How to extract the first set of numbers in a string using PHP

<?php
$str='acc123nmnm4545';
if(preg_match('/\d+/',$str,$arr)){
echo $arr[0];
}
?>

Other ways to extract numbers from strings in PHP

The first method, using regular expressions:

function findNum($str=''){
$str=trim($str);
if(empty($str)){return '';}
$reg='/(\d{3}(.\d+)?)/is';//Regular expression matching numbers
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, using 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, using 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;
}

E.g:

//Intercept the number 2 in the string
$str = 'Q coins 2';
$result='';
for($i=0;$i<strlen($str);$i++){
if(is_numeric($str[$i])){
$result.=$str[$i];
}
}
print_r($result);die;
// output result 2

Top comments (0)