Home  >  Article  >  Backend Development  >  How to replace numbers with php regular

How to replace numbers with php regular

藏色散人
藏色散人Original
2020-08-29 09:39:463857browse

How to implement regular replacement of numbers in php: First create a PHP sample file; then use the regular expression "preg_match_all('/(\d )\.(\d )/is', $total, $arr );" Just replace the numbers in the string.

How to replace numbers with php regular

Recommended: "PHP Video Tutorial"

php regular expression to extract numbers from a string Example

Today I was developing a collector and needed to get numbers from a string. Later I thought of using regular expressions to get them.

Use regular expressions

The code is as follows

$str = ereg_replace(‘[^0-9]‘,”,$str);和
$str = preg_replace( ‘/[^\d]/ ‘, ‘ ‘,$str);

Example

The code is as follows

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 '';
}

If it is a decimal point, our above method is obviously not Correct, we can modify it

The code is as follows

 $regexp = '/(\d+)\.(\d+)/is';
$total = "42.234 EUR 53.218 AUD CAD97.164 311.151 MYR 125.042 NZD GBP84.270 SGD60.227 USD134.400";
preg_match_all('/(\d+)\.(\d+)/is', $total, $arr);
var_export($arr);
 ?>

The result is what we want. If you don’t believe me, go and try it.

The above is the detailed content of How to replace numbers with php regular. 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