Gal*_*led 20
可能?
function split2($string,$needle,$nth){
$max = strlen($string);
$n = 0;
for($i=0;$i<$max;$i++){
if($string[$i]==$needle){
$n++;
if($n>=$nth){
break;
}
}
}
$arr[] = substr($string,0,$i);
$arr[] = substr($string,$i+1,$max);
return $arr;
}
Run Code Online (Sandbox Code Playgroud)
如果你的针总是1个字符,使用Galled的答案,它会更快一点.如果你的$ needle是一个字符串,试试这个.似乎工作正常.
function splitn($string, $needle, $offset)
{
$newString = $string;
$totalPos = 0;
$length = strlen($needle);
for($i = 0; $i < $offset; $i++)
{
$pos = strpos($newString, $needle);
// If you run out of string before you find all your needles
if($pos === false)
return false;
$newString = substr($newString, $pos+$length);
$totalPos += $pos+$length;
}
return array(substr($string, 0, $totalPos-$length),substr($string, $totalPos));
}
Run Code Online (Sandbox Code Playgroud)
这是一种我更喜欢正则表达式解决方案的方法(参见我的其他答案):
function split_nth($str, $delim, $n)
{
return array_map(function($p) use ($delim) {
return implode($delim, $p);
}, array_chunk(explode($delim, $str), $n));
}
Run Code Online (Sandbox Code Playgroud)
只需按以下方式调用:
split_nth("1 2 3 4 5 6", " ", 2);
Run Code Online (Sandbox Code Playgroud)
输出:
array(3) {
[0]=>
string(3) "1 2"
[1]=>
string(3) "3 4"
[2]=>
string(3) "5 6"
}
Run Code Online (Sandbox Code Playgroud)