php正则表达式匹配逗号,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,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

echo $str . "\n";

echo $newstr;

https://3v4l.org/CnSh8

它实际上执行得非常好。比我预期beeing一环,所有中频的和字符串操作

编辑;注意到,它并没有工作,如果第一项是一个字符串我添加一个空格只是为了确保该标志成为以正确的顺序

这可以很容易地进行修整。与trim()。

https://3v4l.org/hNLAF

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值