在php中获取基于范围的索引中的数组值

Ray*_*der 0 php regex arrays controller laravel

我想获得1-3的数组值,但包括'.' 每一次分裂.示例有一个text ="no.this.is.just.example"我想只取0-2索引,所以$ merge将是"no.this.is"

我试过了

$cut = 3;
$text = explode('.',"no.this.is.just.example");

for($i=0; $i<$cut;$i++){
   if($cut-1==$i){
     $merge .= $text[$i];
   }
   else{
     $merge .= $text[$i].'.';
   }
}
Run Code Online (Sandbox Code Playgroud)

有最简单的方法吗?

Moz*_*mil 10

您可以通过使用array_sliceimplode的组合完全避免循环.

$cut = 3;
$text = explode('.', 'no.this.is.just.example');

echo implode('.', array_slice($text, 0, $cut)); 

// outputs no.this.is
Run Code Online (Sandbox Code Playgroud)