php explode delimiter with numbers?
So I'm trying to explode a st开发者_JS百科ring that has a list of answers.
ex: ANSWERS: 1. Comb. 2. Thumb. 3. Tomb (catacomb). 4. Womb. 5. Crumb. 6. Bomb. 7. Numb. 8. Aplomb. 9. Succumb.
Is there a way to explode this to come out like the following:
$answer = explode("something here", $answerString);
$answer[1] = 1. Comb.
$answer[2] = 2. Thumb.
$answer[3] = 3. 3. Tomb (catacomb).
The tricky thing is that I want to explode this string so that each answer can be separated after a number.
So, if the answer is 1 character, or 10 words, it will still split after each number.
Thanks.
No, this is not possible with explode(), but you can use 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 />";
}
}
?>
You probably want to use preg_split()
instead. Something like:
$answer = preg_split('/\d\./', $answerString);
<?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 />";
}
?>
精彩评论