按逗号分隔字符串,但仅按逗号分隔。

3
嗨,我有一个长字符串。
0BV,0BW,100,102,108,112,146,163191,192,193,1D94,19339,1A1,1AA,1AE,1AFD,1AG,1AKF.......

我想通过对它们进行子字符串处理来在页面中展示它们,就像这样。
0BV,0BW,100,102,108,112,146
163191,192,193,1D94,19339
1A1,1AA,1AE,1AFD,1AG,1AKF

我想做的是从字符串中创建长度为100个字符的子字符串,但如果第100个字符不是逗号,则我想要检查字符串中的下一个逗号并按其分割。
我尝试使用chunk()按单词计数拆分,但由于子字符串长度不同,在页面上显示不当。
$db_ocode   = $row["option_code"];

$exclude_options_array =    explode(",",$row["option_code"]);
$exclude_options_chunk_array = array_chunk($exclude_options_array,25);

$exclude_options_string = '';   
foreach($exclude_options_chunk_array as $exclude_options_chunk)
{
    $exclude_options_string .= implode(",",$exclude_options_chunk);
    $exclude_options_string .= "</br>";
}

请帮忙,谢谢。
4个回答

3

取得字符串后,设定截断位置。若该位置不包含逗号,则在该位置之后查找第一个逗号,并在那里截断。简单明了。

<?php

$string="0BV,0BW,100,102,108,112,146,163191,192,193,1D94,19339,1A1,1AA,1AE,1AFD";

$cutoff=30;
if($string[$cutoff]!=",")
  $cutoff=strpos($string,",",$cutoff);
echo substr($string,0,$cutoff);

Fiddle


2
(.{99})(?=,),|([^,]*),

不要使用split方法,而应该使用更简单的捕获方法。请参见包含20个字符的演示。

https://regex101.com/r/sH8aR8/37


1
好答案:)。那个99是打错了吗?因为fiddle是19。哎呀,抱歉不是,因为那个99是OP想要的。 - Hanky Panky
@Hanky웃Panky 没有任何操作员想要 100 个字符。第 100 个字符是在 .{99} 后面的 , - vks

1

使用 Hanky Panky 的回答,我能够为我的问题提供完整的解决方案,非常感谢 Hanky Panky。如果我的代码不够高效,请帮忙修改。

$string="0BV,0BW,100,102,108,112,146,163191,192,193,1D94,19339,1A1,1AA,1AE,1AFD";

for($start=0;$start<strlen($string);) {

       $cutoff=30;
       if(isset($string[$start+$cutoff]) && $string[$start+$cutoff]!=",") 
       {
          $cutoff=strpos($string,",",$start+$cutoff);        
       }
       else if(($start+$cutoff) >= strlen($string))
       {
          $cutoff = strlen($string);
       }
       else if($start >= 30)
       {
          $cutoff = $start + $cutoff;
       }

       echo substr($string,$start,$cutoff-$start)."\n";
       $start=$cutoff+1;
    }

0

如果是Python

ln=0
i=1
str='0BVAa,0BW,100,102,108,112,146,163191,192,193,1D94,19339,1A1,1AA,1AE,1AFD,1AG,1AKF'
for item in str:
    print (item),
    ln=ln+len(item)
    if ln/10>=i and item==',':
        print ""
        i=i+1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接