Split comma separated string but only comma separated
Hello i have a long line
0BV,0BW,100,102,108,112,146,163191,192,193,1D94,19339,1A1,1AA,1AE,1AFD,1AG,1AKF.......
I want to show it on the page by adding them
as
0BV,0BW,100,102,108,112,146 163191,192,193,1D94,19339 1A1,1AA,1AE,1AFD,1AG,1AKF
I want to create substrings from a 100 character long string, but if the 100th character is not a comma, I want to check for the next comma in the string and split by it.
I tried to use chunk()
to split by word count, but since the length of the substring is different, it is displayed on the page
$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>";
}
Please, help. thank you in advance
source to share
Take a string, set the cutoff position. If this position does not contain a comma, then find the first comma after that position and cut it off. Plain
<?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);
source to share
Using Hanky Panky's answer I was able to provide a complete solution to my problem, many thanks to Hanky panky. If my code is not efficient, please edit it.
$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;
}
source to share