stursby stursby - 2 days ago 4
PHP Question

php explode delimiter with numbers?

So I'm trying to explode a string 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.

Answer

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 />"; 
    } 
} 
?>
Comments