如何在PHP中截断分隔的字符串?

I have a string of delimited numerical values just like this:

5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324|9004| ...etc.

Depending on the circumstance, the string may have only 1 value, 15 values, all the way up to 100s of values, all pipe delimited.

I need to count off (and keep/echo) the first 10 values and truncate everything else after that.

I've been looking at all the PHP string functions, but have been unsuccessful in finding a method to handle this directly.

Use explode() to separate the elements into an array, then you can slice off the first 10, and implode() them to create the new string.

$arr = "5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324|9004";
$a = explode ('|',$arr);
$b = array_slice($a,0,10);
$c = implode('|', $b);

Use PHP Explode function

$arr = explode("|",$str);

It will break complete string into an array. EG: arr[0] = 5, arr[1] = 2288 .....

I would use explode to separate the string into an array then echo the first ten results like this

$string = "5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324|9004";

$arr = explode("|", $string);

for($i = 0; $i < 10; $i++){
    echo $arr[$i];
}

Please try below code

$str = '5|2288|502|4208|55|23217|235|10|3845|19053|1885|61|324';


$arrayString = explode('|', $str);
$cnt = 0;
$finalVar = '';
foreach ($arrayString as $data) {
    if ($cnt > 10) {
        break;
    }

    $finalVar .= $data . '|';
    $cnt++;
}
$finalVar = rtrim($finalVar, '|');
echo $finalVar;