如何在第n次发生针时在PHP中拆分字符串?

Dɑv*_*vïd 23 php string

必须有一种快速有效的方法在针的"第n"次出现时分割(文本)字符串,但我找不到它.PHP手册中的strpos注释中有一套相当完整的函数,但这似乎对我需要的东西有点多.

我有纯文本$string,并希望在第n次出现时拆分它$needle,在我看来,needle它只是一个空格.(我可以做理智检查!)

有人能指出我正确的方向吗?非常感谢!

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)

  • 仅适用于一个字符大小长度的$ needle (3认同)

Joh*_*ohn 9

如果你的针总是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)


Chr*_*rle 8

就个人而言,我只是把它分成一个爆炸的阵列,然后将第一n-1部分作为上半部分内爆,并将剩下的数字作为下半部分内爆.


Mat*_*hew 5

这是一种我更喜欢正则表达式解决方案的方法(参见我的其他答案):

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)

  • 当然,这解决了一个稍微不同的问题——不是“拆分 AT *nth* 个字符”而是“拆分每个 *nth* 个字符。不完全是我的场景!不过可能对其他人有用。谢谢! (3认同)