如何在第三次出现时拆分字符串


How can I split a string on the third occurrence of something?

我知道" explosion "拆分字符串并将其转换为每次出现的数组。但我如何在第三次发生时分割并保留第三次发生后的所有内容?

例子1 :

$split = explode(':', 'abc-def-ghi::State.32.1.14.16.5:A);

我想输出:

echo $split[0];  // abc-def-ghi::State.32.1.14.16.5
echo $split[1];  // A

例子2 :

$split = explode(':', 'def-ghi::yellow:abc::def:B);

我想输出:

echo $split[0];  // def-ghi::yellow
echo $split[1];  // abc::def:B

使用分隔符拆分字符串,并返回在该分隔符出现第n次时拆分的两个字符串。

  • 1)使用分隔符爆炸
  • 2)如果设置了所需的数组项,则查找该字符串在原始源中的位置。
  • 3)在该字符串的位置分成两个字符串

在eval.in

代码:

<?php
/**
 * Split a string using a delimiter and return two strings split on the the nth occurrence of the delimiter.
 *  @param string  $source
 *  @param integer $index - one-based index
 *  @param char    $delimiter
 *
 * @return array  - two strings 
 */
function strSplit($source, $index, $delim)
{
  $outStr[0] = $source;
  $outStr[1] = '';
  $partials = explode($delim, $source);
  if (isset($partials[$index]) && strlen($partials[$index]) > 0) {
     $splitPos = strpos($source, $partials[$index]);
     $outStr[0] = substr($source, 0, $splitPos - 1);
     $outStr[1] = substr($source, $splitPos);
  }
  return $outStr;
}
测试:

$split = strSplit('abc-def-ghi::State.32.1.14.16.5:A', 3, ':');
var_dump($split);
$split1 = strSplit('def-ghi::yellow:', 3, ':');
var_dump($split, $split1);
输出:

array(2) {
  [0]=>
  string(31) "abc-def-ghi::State.32.1.14.16.5"
  [1]=>
  string(1) "A"
}
array(2) {
  [0]=>
  string(31) "abc-def-ghi::State.32.1.14.16.5"
  [1]=>
  string(1) "A"
}
array(2) {
  [0]=>
  string(16) "def-ghi::yellow:"
  [1]=>
  string(0) ""
}

遗憾的是,还没有人提供preg_split()——所以我将提供。

您只需要匹配三次后面跟着冒号的非冒号交替序列。我把'K写在:之前,这样在爆炸期间只有第三个冒号被消耗。为了确保不使用任何字符,只需将'K移动到模式的末尾(就在结束的/之前)。在我的模式中,*表示"零个或多个符合前一个规则的连续字符"。[^:]表示任何非冒号字符。

要将输出数组的大小限制为最多2个元素,请使用2作为第三个函数参数。如果没有限制参数,那么在输出中创建更多元素时可能会消耗第6、第9等冒号。如果由于输入字符串的结构而在输出中遇到不需要的空元素,可以使用PREG_SPLIT_NO_EMPTY作为第四个函数参数来省略它。

代码(演示):

preg_split(
    '/(?:[^:]*'K:){3}/',
    $string,
    2
)

abc-def-ghi::State.32.1.14.16.5:A变为:

array (
  0 => 'abc-def-ghi::State.32.1.14.16.5',
  1 => 'A',
)

def-ghi::yellow:abc::def:B变为:

array (
  0 => 'def-ghi::yellow',
  1 => 'abc::def:B',
)

首先用分隔符

分隔字符串
$x = explode(':', $string) 

然后找到你需要的索引,希望是$x[2]

然后连接前两个

$first_half = $x[0].$x[1]

然后内爆$x[2]之后的任何东西

$second_half = implode(':', array_slice($x, 2))

首先由::分割并获得两个输出。
现在,通过:拆分进一步的输出并获得单独的字符串。

最后,根据您的需要追加所需的字符串以获得精确的输出:

<?php
  $str = "abc-def-ghi::State.32.1.14.16.5:A";
  $split1 = explode('::', $str)[0];
  $split2 = explode('::', $str)[1];
  $split3 = explode(':', $split2)[0];
  $split4 = explode(':', $split2)[1];
  echo $split1 . "::" . $split3;
  echo $split4;
?>