PHP将字符串拆分为数组

时间:2013-12-04 09:18:02

标签: php

我正在尝试将字符串拆分为数组。这是我的数据:

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

3 个答案:

答案 0 :(得分:3)

我认为这就是你想要的

$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时,您必须在正则表达式中提供()捕获模式

<强>已更新

更新了正则表达式以支持字符串

中的数字

答案 1 :(得分:0)

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

答案 2 :(得分:-1)

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

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