分割後の区切り文字を使用して文字列を何かを内破し、区切り文字の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) ""
}
使用するpreg_split。 explode()は単純な文字列演算であり、preg_splitは正規表現を使用し、複雑な分割点を指定する方がずっと簡単です。 –