如何从字符串中的其他逗号中删除逗号?

时间:2019-04-10 15:43:30

标签: php arrays string preg-replace str-replace

我正在使用包含帐户对帐单的数组。我希望能够从数字值中删除逗号,以便能够在不损失生命值的情况下以逗号爆炸。

例如,我的数组包含如下索引:

26 => 20/08/2099,"ATM CASH WITHDRAWAL (ON-US) ATM CASH WITHDRAWAL (ON-US) EMPEMOM, LAGA ATM 2 LOGO NG 000360585490","",20/08/2018,"5,000","","1,316.01"

27 => 27/08/2027,BANK CHARGE 26 SMS CHARGE AND VAT FOR 27TH JUL - 23RD AUG 2018,2803064 028,27/08/2018,109.2,"","1,206.81"

我想删除“ 5,000”和其他货币值中的逗号,而不删除每个字符串之间的逗号,以便输出看起来像:

26 => 20/08/2099,"ATM CASH WITHDRAWAL (ON-US) ATM CASH WITHDRAWAL (ON-US) EMPEMOM, LAGA ATM 2 LOGO NG 000360585490","",20/08/2018,"5000","","1316.01"

27 => 27/08/2027,BANK CHARGE 26 SMS CHARGE AND VAT FOR 27TH JUL - 23RD AUG 2018,2803064 028,27/08/2018,109.2,"","1206.81"

2 个答案:

答案 0 :(得分:1)

您还可以将array_mappreg_replace_callback一起使用,并可以将其用作模式:

"\d{1,3}(?:,\d{3})+\.\d{2}"
  • "\d{1,3}匹配",后接1-3位数字
  • (?:,\d{3})!重复1次以上以匹配逗号和3位数字
  • \.\d{2}"匹配一个点和一个2位数字,后跟"

Regex demo | Php demo

preg_replace_callback的回调中,用一个空字符串替换逗号并返回匹配项。

例如:

$atm = array(
    '26' => '20/08/2099,"ATM CASH WITHDRAWAL (ON-US) ATM CASH WITHDRAWAL (ON-US) EMPEMOM, LAGA ATM 2 LOGO NG 000360585490","",20/08/2018,"5,000","","1,316.01"',
    '27' => '27/08/2027,BANK CHARGE 26 SMS CHARGE AND VAT FOR 27TH JUL - 23RD AUG 2018,2803064 028,27/08/2018,109.2,"","1,206.81"'
);

$atm = array_map(function($x) {
    return preg_replace_callback('/"\d{1,3}(?:,\d{3})+\.\d{2}"/', function($m) {
       return  str_replace(',', '', $m[0]);
    }, $x);
}, $atm);

print_r($atm);

结果:

Array
(
    [26] => 20/08/2099,"ATM CASH WITHDRAWAL (ON-US) ATM CASH WITHDRAWAL (ON-US) EMPEMOM, LAGA ATM 2 LOGO NG 000360585490","",20/08/2018,"5,000","","1316.01"
    [27] => 27/08/2027,BANK CHARGE 26 SMS CHARGE AND VAT FOR 27TH JUL - 23RD AUG 2018,2803064 028,27/08/2018,109.2,"","1206.81"
)

答案 1 :(得分:0)

您可以使用foreach数组并以逗号爆炸,然后替换为“,”每个数组,然后检查其是否为数字

foreach数组然后用逗号爆炸字符串

$stringArray=explode(",",$str)

然后在每个$ stringArray中替换“,”

$CheckNumber= str_replace(',', '', $string);

并通过以下方式检查是否为数字:

if (is_numeric($CheckNumber))
   $stringArray[i]=$CheckNumber;

最后加入数组

join(",",$stringArray);