2012-05-11 149 views

回答

4

较大或较小的使用爆炸/破灭:

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

使用正则表达式:

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

如果你打算使用'explode'为此,传递设置为1'limit'第三个参数+你想限制无用功的项目数。 http://php.net/manual/en/function.explode.php –

1

地尝试一下PHP的explode()功能。

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

遍历数组得到你想要的值:

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

一种方法是在一个逗号后面的字符串分割,并把第100个指数一起(以逗号分隔)。 在此之前,你必须检查是否计数(阵列)比100

1

你可以这样做的找到第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";