简体   繁体   中英

PHP splitting a string into an 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);

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 eg 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM