2017-08-10 265 views
1

我有串在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需要什麼?謝謝

+2

爲什麼不使用[str_getcsv()](http://php.net/manual/en/function.str-getcsv.php)將字符串解析爲數組而不是試圖「修復」它與正則表達式? –

+0

我不知道這個功能,謝謝! –

回答

1

我只是想嘗試做一個代碼,可以做到這一點老式的方式。
它發現「,並根據它是否是他們之間或他們的外面或不替換。

$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,0'; 

$pos=1; // set $pos to make sure while loop does not end directly. 
$newstr = ""; 
$prevPos = 0; 
if($str[0]=='"') $str = " " .$str; // add space if the first char is a " 
$skip = false; // flag to know if replace should be done or not 

while($pos != false){ 
    $pos = strpos($str, '"', $prevPos); // find " in string after prevPos 
    $part = substr($str, $prevPos, $pos+1-$prevPos); // substring the part (first time it runs it will be '1,"' then '4052"') 
    if($skip){ // if it's between two " (a string) skip the replace 
     //echo "skip " . $part . "\n"; 
     $skip =!$skip; // change the flag 
     $newstr .= $part; 
    }else{ // if it's not in a string do the replace on the $part 
     //echo "!skip " . $part . "\n"; 
     $newstr .= str_replace(",", ";", $part);  
     $skip =!$skip; // change the flag. 
    } 
    $prevPos = $pos+1; // set new $prevPos 
} 

// if the loop ends and there is no more " in the string we need to replace , to ; on the rest of the string. 
// we know the loop ended at strlen($newstr), so that is the $part. 
if($pos<strlen($str)) $newstr .= str_replace(",", ";", substr($str, strlen($newstr))); 
echo $str . "\n"; 
echo $newstr; 

https://3v4l.org/CnSh8
它實際上執行得非常好。比我預期beeing一環,所有中頻的和字符串操作

編輯;注意到,它並沒有工作,如果第一項是一個字符串我添加一個空格只是爲了確保該標誌成爲以正確的順序
這可以很容易地進行修整。與trim()。
https://3v4l.org/hNLAF

+0

似乎有效!謝謝你的建議! –

相關問題