2015-07-20 138 views
-1

我有這樣使preg_split與關閉標籤

$string = '[c]str1[/c][c]str2[/c][c]str3[/c][c]str4[/c][c]str5[/c]'; 

我想分割它獲得所有strX陣列中的一個串

到目前爲止,我成功地做到這樣

$strarray = preg_split('/\[.](.*?)\[\/.]/', $string, -1, PREG_SPLIT_DELIM_CAPTURE); 

但我得到的結果是

array (
    0 => '', 
    1 => 'str1', 
    2 => '', 
    3 => 'str2', 
    4 => '', 
    5 => 'str3', 
    6 => '', 
    7 => 'str4', 
    8 => '', 
    9 => 'str5', 
    10 => '', 
) 

是否有任何正則表達式模式直接擺脫空白數組元素(我不想通過$ strarray來刪除空白元素,除非它是唯一的解決方案)?

回答

3

你應該使用preg_splitPREG_SPLIT_NO_EMPTY標誌:

PREG_SPLIT_NO_EMPTY
如果設置了此標誌,則只有非空的部分將由preg_split()返回。

代碼:

$strarray = preg_split('/\[.](.*?)\[\/.]/', $string, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY); 

IDEONE demo

輸出:

Array 
(
    [0] => str1 
    [1] => str2 
    [2] => str3 
    [3] => str4 
    [4] => str5 
) 
0

使用preg_match_all

preg_match_all('~\[.]\K.*?(?=\[\/.])~', $str, $matches); 

preg_match_all('~\[(.)]\K.*?(?=\[\/\1])~', $str, $matches); 

DEMO