php 如何在不分隔值的情况下在数组中添加逗号?

php How to add comma's in an array without making it separate values?

我的字符串:

'KCP-PRO;first_name last_name;address;zipcode;country' //for example: 'KCP-PRO;Jon Doe;Box 564;02201;USA'
or
'KCP-SAT-PRO;first_name last_name;address;zipcode;country'

如何更改第一部分(KCP-PRO 或 KCP-SAT-PRO)并将其更改为(KCP,PRO 或 KCP,SAT,PRO)?结果必须是:

'KCP,PRO;first_name last_name;address;zipcode;country'
or
'KCP,SAT,PRO;first_name last_name;address;zipcode;country'

我自己还没有尝试过代码,但我想这可以解决问题

$string = 'KCP-SAT-PRO;first_name last_name;address;zipcode;country';

$stringExploded = explode(';', $string);
$stringExploded[0] = str_replace('-', ',', $stringExploded[0]);
$output = implode(';', $stringExploded);

//output should be KCP,SAT,PRO;first_name last_name;address;zipcode;country

希望这对您有所帮助:)

或者您可以使用带有以下正则表达式的 preg_replace_callback 函数

^[^;]*

所以你的代码看起来像

echo preg_replace_callback("/^[^;]*/",function($m){
     return str_replace("-",',',$m[0]);
},"KCP-SAT-PRO;first_name last_name;address;zipcode;country");