regular expression to consider periods after numer

2019-07-11 05:20发布

I have the following code

<?php
$str="$str="115(JOHN DOE.)      900,000.00 SALARY.    45 AGE.   "; 
$str=preg_replace("/[a-zA-Z(),]/", "", $str);          
echo $str=preg_replace('!\s+!', ',', $str);
?>

This output

115,.,900000.00.,45.,

but this is not exactly what i need, i need to consider period which is inside 900,000.00 and ignore that of JOHN DOE. , SALARY.,AGE.

How can i do that to get

115,900000.00,45

I.e i need regular expression to consider periods after numeric character only

3条回答
啃猪蹄的小仙女
2楼-- · 2019-07-11 05:56

Without trying to improve your code...this should do it:

$str="115(JOHN DOE.)      900,000.00(SALARY.)    45(AGE.)";
$str=preg_replace("/[a-zA-Z]+\.+/", "", $str);
$str=preg_replace("/[a-zA-Z(),]/", "", $str);
echo $str=preg_replace('!\s+!', ',', $str);
查看更多
萌系小妹纸
3楼-- · 2019-07-11 06:04

I made it in three steps:

$a = "115(JOHN DOE.)      900,000.00(SALARY.)";
$a = preg_replace("/\([A-Z ]*\.\)/", "", $a);          // 115      900,000.00
$b = preg_replace("/,/", "", $a);                     // 115      900000.00
$c = preg_replace("/\s+/", ",", $b);                  // 115,900000.00

You can change this line:

$a = preg_replace("/\([A-Z ]*\.\)/", "", $a);

with this:

$a = preg_replace("/[A-Z ]*\./", "", $a);

to remove data without parentheses.

查看更多
来,给爷笑一个
4楼-- · 2019-07-11 06:15
$str = '115(JOHN DOE.)      900,000.00 SALARY.    45 AGE. ';
preg_match_all("/\d+(?:(?:[,.]\d+)+)?/", $str, $match);
$match = array_map(function($val) { return str_replace(",", "", $val); }, $match[0]);
echo implode(",", $match);

Output:

115,900000.00,45
查看更多
登录 后发表回答