How to get a substring of comma delimited string?

I have a comma delimited string and want the first 100 entries (not counting the 100th comma) to be a single line.

So for example, if I had a line

a,b,c,d,e,f,g

And the problem was getting the first three entries, the desired result line would be

a,b,c
+3
source share
4 answers

Using explode / implode:

$str     = 'a,b,c,d,e,f,g';
$temp1   = explode(',',$str);
$temp2   = array_slice($temp1, 0, 3);
$new_str = implode(',', $temp2);

Using regex:

$new_str = preg_replace('/^((?:[^,]+,){2}[^,]+).*$/','\1',$str);
+4
source

try php function explode () .

$string_array = explode(",",$string);

Scroll through the array to get the values ​​you need:

for($i = 0; $i < sizeof($string_array); $i++)
{
echo $string_array[$i];//display values
}
+1
source

, 100- :

$delimiter = ',';
$count = 100;
$offset = 0;
while((FALSE !== ($r = strpos($subject, $delimiter, $offset))) && $count--)
{
    $offset = $r + !!$count;
}
echo substr($subject, 0, $offset), "\n";

:

$delimiter = ',';
$count = 100;
$len = 0;
$tok = strtok($subject, $delimiter);
while($tok !== FALSE && $count--)
{
    $len += strlen($tok) + !!$count;
    $tok = strtok($delimiter);
}
echo substr($subject, 0, $len), "\n";
+1

- 100 ( ). , () 100.

0

All Articles