我有串在PHPPHP - 正则表达式,替换逗号分隔符,以分号
$str = '1,"4052","B00K6ED81S",,"Bottle, white - 6,5 l, WENKO","Good design!","Bottle, white 6,5 l, WENKO",,,"item","23",23,"23",23,31.22,31.22,,1,,,,0,8,"4",,0,,0,0,,0,,0,0,,
有逗号分隔符。某处是空的字段,某处带有引号的字段(作为产品名称)。问题在于将分隔符替换为分号,但不要在产品名称中使用逗号。我需要这样的:
$str_replace = '1;"4052";"B00K6ED81S";;"Bottle, white - 6,5 l, WENKO";"Good design!";"Bottle, white 6,5 l, WENKO";;;"item";"23";23;"23";23;31.22;31.22;;1;;;;0;8;"4";;0;;0;0;;0;;0;0;;';
我试过这段代码:
$str = '1,"4052","B00K6ED81S",,"Bottle, white - 6,5 l, WENKO","Good design!","Bottle, white 6,5 l, WENKO",,,"item","23",23,"23",23,31.22,31.22,,1,,,,0,8,"4",,0,,0,0,,0,,0,0,,';
$str = preg_replace('/,,/', ',~~~,', $str);
$str = preg_replace('/,,/', ',~~~,', $str);
$pattern = '/(?<=\d),|(?<="),|~~~,/';
$str = preg_replace($pattern, ';', $str);
结果:
1;"4052";"B00K6ED81S";;"Bottle, white - 6;5 l, WENKO";"Good design!";"Bottle, white 6;5 l, WENKO";;;"item";"23";23;"23";23;31.22;31.22;;1;;;;0;8;"4";;0;;0;0;;0;;0;0;;
在产品的名称逗号替换以分号太:
"Bottle, white - 6;5 l, WENKO"
如何我可以更正$ pattern来获得结果I需要什么?谢谢
为什么不使用[str_getcsv()](http://php.net/manual/en/function.str-getcsv.php)将字符串解析为数组而不是试图“修复”它与正则表达式? –
我不知道这个功能,谢谢! –