phpregexstringsplitexplode

Split string only at spaces followed by word then a colon


I have a string $str which holds the below information

Cricket Batting:India Score:99/2 Date:27 June 2013

I want break this string into 4 parts and that should be like this:

$part1 = "Cricket";
$part2 = "Batting:India";
$part3 = "Score:99/2";
$part4 = "Date:27 June 2013";

I tried using explode() but the problem is values doesn't stand same always. For example it could be:

Cricket Batting:South Africa Score:203/10 Date:7 May 2013
or this:
Cricket Batting:Australia Score:1/1 Date:27 September 2019

So, when I use explode South and africa will split into different variables. I can't use wordwrap() as length of the string varies from time to time.


Solution

  • You can use preg_split with this pattern:

    ~ (?=Batting|Score|Date)~