2011-09-21 60 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 />"; 
    } 
?>