Search code examples
phpsplit

Split a single-line string containing a numbered list into a flat array


I am trying to split an string into an array. This is my data:

1. Some text is here!!! 2. Some text again 3. SOME MORE TEXT !!!

I would like an array to be like this:

Array(
 [0] => '1. Some text here!!!
 [1] => '2. Some text again
 etc..
);

I tried this using preg_split but can't get it right


$text = "1. Some text is here!!! 2. Some text again 3. SOME MORE TEXT !!!";
$array = preg_split('/[0-9]+./', $text, NULL, PREG_SPLIT_NO_EMPTY);

print_r($array);

Solution

  • I think this is what you want

    $text  = "1. Some text is here333!!! 2. Some text again 3. SOME MORE TEXT !!!";
    $array = preg_split('/(\d+\..*?)(?=\d\.)/', $text, NULL, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
    
    print_r($array);
    Array
    (
        [0] => 1. Some text is here333!!! 
        [1] => 2. Some text again 
        [2] => 3. SOME MORE TEXT !!!
    )
    

    Why it works?

    First of all, preg_split by default doesn't keep the delimiters after splitting a string. That's why your code doesn't contain number e.g. 1, 2 etc

    Secondly, when using PREG_SPLIT_DELIM_CAPTURE you must provide () capturing pattern in your regex

    UPDATED

    Updated regex to support number in string