Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP-REGEX - Multiple Choice Type

Tags:

regex

css

php

I have a string like this:

$str = "1. What is love? a. Haddaway b. Haxxaway c. Hassaway d. Hannaway 2. What is love? a. Haddaway b. Haxxaway c. Hassaway d. Hannaway"

What I want to do is to have an output like this and store each question to a div:

1. What is love? 
a. Haddaway b. Haxxaway c. Hassaway d. Hannaway 

2. What is love? 
a. Haddaway b. Haxxaway c. Hassaway d. Hannaway 

As of the moment, I created this made-up code for regex (still a newbie, sorry!)

$str = "1. What is love? a. Haddaway b. Haxxaway c. Hassaway d. Hannaway 2. What is love? a. Haddaway b. Haxxaway c. Hassaway d. Hannaway"
$repl = preg_replace('#(\d+:.*?)(?=\d+:|$) *#', "$1", $str);
echo "<div>$repl</div>";

And the output is this and it's stored on a single div:

1. What is love? a. Haddaway b. Haxxaway c. Hassaway d. Hannaway 2. What is love? a. Haddaway b. Haxxaway c. Hassaway d. Hannaway

I'm confused on how to separate each question and how to put a div on each choice... can anyone give some advice on what should I do?

like image 828
DaLoco Avatar asked Mar 07 '26 16:03

DaLoco


1 Answers

You can use preg_split like this:

$str = "1. What is love? a. Haddaway b. Haxxaway c. Hassaway d. Hannaway 2. What is love? a. Haddaway b. Haxxaway c. Hassaway d. Hannaway";

print_r(preg_split('/(?=[a\d]+\.)/', $str, -1, PREG_SPLIT_NO_EMPTY));
Array
(
    [0] => 1. What is love?
    [1] => a. Haddaway b. Haxxaway c. Hassaway d. Hannaway
    [2] => 2. What is love?
    [3] => a. Haddaway b. Haxxaway c. Hassaway d. Hannaway
)

(?=[a\d]+\.) is a lookahead that splits when followed by number or letter a plus a DOT.

like image 146
anubhava Avatar answered Mar 10 '26 04:03

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!