2016-08-17 5 views
0

"explode"は文字列を分割し、それをすべてのオカレンスに対して配列に変換することを知っています。しかし、どのように私は3番目の発生に分割し、3番目の発生後のすべてを保持するのですか?3番目の出現時に文字列を分割するにはどうすればよいですか?

例1

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

I出力にこれを希望:

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

をI出力にこれを希望:

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

使用するpreg_split。 explode()は単純な文字列演算であり、preg_splitは正規表現を使用し、複雑な分割点を指定する方がずっと簡単です。 –

答えて

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

このコードスニペットは問題を解決するかもしれませんが、[説明を含む](// meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)本当にあなたの投稿の質を向上させるのに役立ちます。将来読者の質問に答えていることを覚えておいてください。そうした人々はあなたのコード提案の理由を知らないかもしれません。また、コードと説明の両方の可読性が低下するため、説明的なコメントを使用してコードを混乱させないようにしてください。 – FrankerZ

0

まず次に$x[2]

うまくいけば、あなたが必要なインデックスを見つける区切り文字で

$x = explode(':', $string) 

を文字列を爆発

その後、最初の2つを連結します。

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

その後$x[2]

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

分割後の区切り文字を使用して文字列を何かを内破し、区切り文字のn番目の発生に分割し2つの文字列を返します。

  • 1)デリミタを使用して爆発します。
  • 2)必要な配列エントリが設定されている場合は、元のソースのその刺し傷の位置を見つけます。
  • 3)その文字列の位置で2つの文字列に分割します。

Demonstration at 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) "" 
} 
関連する問題