如何在第三次出现的事情上拆分字符串?

时间:2016-08-17 15:44:29

标签: php

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

示例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

3 个答案:

答案 0 :(得分:0)

说明:

First split by :: and get both the output
Now, split further output by : and get individual strings
Last, append required strings according to your requirements to get exact output.

代码:

<?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;
?>

答案 1 :(得分:0)

首先通过分隔符

爆炸字符串
$x = explode(':', $string) 

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

然后连接前两个。

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

然后在$x[2]

之后内爆任何内容
$second_half = implode(':', array_slice($x, 2))

答案 2 :(得分:0)

使用分隔符拆分字符串,并返回在分隔符的第n个匹配项上拆分的两个字符串。

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

Demonstration at eval.in

代码:

public function getDateToAttribute($value)
{
    return Carbon::parse($value)->format('d-m-Y');
}

测试:

<?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);