Sadly, no one has offered preg_split()
yet -- so I will.
You merely need to match alternating sequences of non-colons followed by a colon three times. I have written \K
before the :
so that only the third occuring colon is consumed during the explosion. To ensure that no characters are consumed, just move the \K
to the end of the pattern (just before the closing /
). *
in my pattern means "zero or more continuous characters obeying the preceding rule". [^:]
means any non-colon character.
To limit the size of the output array to a maximum of 2 elements, use 2
as the third function parameter. Without the limiting parameter, then it is possible that the 6th, 9th, etc colons will be consumed while creating more elements in the output. If you encounter an unwanted empty element in the output because of the structure of your input string, you can use PREG_SPLIT_NO_EMPTY
as the fourth function parameter to omit it.
Code: (Demo)
preg_split(
'/(?:[^:]*\K:){3}/',
$string,
2
)
abc-def-ghi::State.32.1.14.16.5:A
becomes:
array (
0 => 'abc-def-ghi::State.32.1.14.16.5',
1 => 'A',
)
def-ghi::yellow:abc::def:B
becomes:
array (
0 => 'def-ghi::yellow',
1 => 'abc::def:B',
)