Haagenti
Haagenti

Reputation: 8144

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

Upvotes: 1

Views: 116

Answers (3)

Rezigned
Rezigned

Reputation: 4932

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

Upvotes: 3

Maciej Sz
Maciej Sz

Reputation: 12035

$str = "1. Some text is here!!! 2. Some text again 3. SOME MORE TEXT !!!";

preg_match_all('#[0-9]+\\.#', $str, $matches, PREG_OFFSET_CAPTURE);


$exploded = array();
$previous = null;
foreach ( $matches[0] as $item ) {
    if ( $previous !== null ) {
        $exploded[] = substr($str, $previous, $item[1]);
    }
    $previous = $item[1];
}
if ( $previous !== null ) {
    $exploded[] = substr($str, $previous);
}

var_export($exploded);

Upvotes: 0

po_taka
po_taka

Reputation: 1856

$a = '1. Some text is here!!! 2. Some text again 3. SOME MORE TEXT !!!';

$array = preg_split('/([0-9]+\\.)/', $a, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);

var_dump($array);

Result:

array (size=6)
  0 => string '1.' (length=2)
  1 => string ' Some text is here!!! ' (length=22)
  2 => string '2.' (length=2)
  3 => string ' Some text again ' (length=17)
  4 => string '3.' (length=2)
  5 => string ' SOME MORE TEXT !!!' (length=19)

Then you have to concatenate 1st and 2nd index, 3rd and 4th etc....

Upvotes: -1

Related Questions