PHP将字符串拆分为数组


PHP splitting a string into an array

我正试图将一个字符串拆分为一个数组。这是我的数据:

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

我希望阵列是这样的:

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

我用preg_split尝试过这个,但不能得到正确的


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

我想这就是你想要的

$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 !!!
)

为什么它有效

首先,默认情况下,preg_split在拆分字符串后不保留分隔符。这就是为什么你的代码不包含数字,例如1、2等

其次,当使用PREG_SPLIT_DELIM_CAPTURE时,必须在正则表达式中提供()捕获模式

更新

更新regex以支持字符串中的数字

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

结果:

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)

然后你必须连接第一个和第二个索引,第三个和第四个等等…