2011-09-21 64 views
1

所以我試圖炸開一個有答案列表的字符串。php爆炸分號與數字?

例如:答案:1.梳子。 2.拇指。 3.墓(地下墓穴)。子宮。 5.麪包屑。炸彈。 7.麻木。 8. Aplomb。 9.沉迷。

有沒有辦法爆炸這個出來像下面這樣:

$answer = explode("something here", $answerString); 
$answer[1] = 1. Comb. 
$answer[2] = 2. Thumb. 
$answer[3] = 3. 3. Tomb (catacomb). 

棘手的是,我想爆炸此字符串,這樣每個答案可以在號碼後分開。

因此,如果答案是1個字符或10個單詞,它仍然會在每個數字後分裂。

謝謝。

+2

有這樣做,如果一個答案本身就含有像'「測試5. 6. 7.」'沒有完美的方法。我認爲你最好把源輸入變成更好的格式。 –

+0

你的意思是'$ answer [2] =「3.墓(地下墓穴)。」'? (注意你的數組索引從1開始而不是0,在你的例子中你有兩個'3's) – CanSpice

回答

7

不,這是不可能的爆炸(),但你可以使用preg_split()

http://sandbox.phpcode.eu/g/4b041/1

<?php 
$str = '1. Comb. 2. Thumb. 3. Tomb (catacomb). 4. Womb. 5. Crumb. 6. Bomb. 7. Numb. 8. Aplomb. 9. Succumb'; 
$exploded = preg_split('/[0-9]+\./', $str); 
foreach($exploded as $index => $answer){ 
    if (!empty($answer)){ 
     echo $index.": ".$answer."<br />"; 
    } 
} 
?> 
4

你可能想使用preg_split()代替。喜歡的東西:

$answer = preg_split('/\d\./', $answerString); 
0
<?php 
$org_string = "1. Comb. 2. Thumb. 3. Tomb (catacomb). 4. Womb. 5. Crumb. 6. Bomb. 7. Numb. 8. Aplomb. 9. Succumb"; 
$new_string = str_replace("b. ", "b. ,", $org_string); 
$final_string = str_replace("b). ", "b). ,", $new_string); 
$exploded = explode(" ,",$final_string); 
foreach($exploded as $answer){ 

     echo $answer."<br />"; 
    } 
?>