2015-04-01 102 views
3

我想要做的是將一個PHP字符串分成一組子字符串,這些子字符串根據開始這些子字符串的「divider」字符分組爲數組。字符*,^%被保留爲分隔符。所以,如果我有串"*Here's some text^that is meant*to be separated^based on where%the divider characters^are",應該分裂並放置在陣列像這樣:根據「divider」字符將PHP字符串劃分爲排列的子字符串

array(2) { 
    [0] => "*Here's some text" 
    [1] => "*to be separated" 
} 

array(3) { 
    [0] => "^that is meant" 
    [1] => "^based on where" 
    [2] => "^are" 
} 

array(1) { 
    [0] => "%the divider characters" 
} 

我完全失去了在這一個。有誰知道如何實現這一點?

+0

你試過explode()函數嗎? – Maximus2012 2015-04-01 19:21:05

+0

「分隔符」的編程術語是分隔符。 – 2015-04-01 19:38:03

+0

感謝您的提示。我不知道。 – vdubguy777 2015-04-01 20:09:52

回答

2

,如果你想你不爲$matches[0]所以取消它問:

preg_match_all('/(\*[^\*\^%]+)|(\^[^\*\^%]+)|(%[^\*\^%]+)/', $string, $matches); 
$matches = array_map('array_filter', $matches); 

print_r($matches); 

array_filter()去除捕獲組子陣列空瓶給在這個問題

+0

'array_map('array_filter'' really?why not'unset'? – 2015-04-01 19:29:09

+1

'array_filter'去除其他空容器。這將是一個循環和多個unsets – AbraCadaver 2015-04-01 19:29:53

0

另一個所示的陣列方法(優化)..

$matches = array(); 
preg_match_all('/[\*\^\%][^\*\^\%]+/', $str, $matches); 
var_dump($matches); 
相關問題