我有串在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)將字符串解析爲數組而不是試圖「修復」它與正則表達式? –
我不知道這個功能,謝謝! –