Home > Backend Development > PHP Problem > How to convert numbers in string to array in php

How to convert numbers in string to array in php

coldplay.xixi
Release: 2023-03-03 21:02:02
Original
3658 people have browsed it

php method to convert numbers in a string into an array: 1. Use the regular expression method, the code is [$reg='/(\d{3}(\.\d )?)/ is']; 2. Use the [in_array] method, the code is [if(in_array($str[$i],$temp))].

How to convert numbers in string to array in php

php method to convert numbers in a string into an array:

The first method , use 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, 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

Related learning recommendations: php programming (video)

The above is the detailed content of How to convert numbers in string to array in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
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