簡體   English   中英

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 ,必須在正則表達式中提供()捕獲模式

更新

更新了正則表達式以支持字符串中的數字

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

然后,您必須連接第一和第二索引,第三和第四索引等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM