RegExp将逗号分隔符替换为分号

时间:2017-08-10 19:29:28

标签: php regex preg-replace

我在PHP中有字符串

$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以获得我需要的结果?

1 个答案:

答案 0 :(得分:1)

我只是想尝试制作一个可以用老式方式做到的代码 它找到了&#34;并且根据它们之间或它们之间是否有替换。

$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
它实际上表现得相当不错。比我预期的要好一个循环以及所有if和#string操作。

EDIT;注意到如果第一项是字符串,它就不起作用。我添加一个空格只是为了确保标志的顺序正确 这可以通过trim()轻松修剪 https://3v4l.org/hNLAF