Put string value of html to array by php regex

i have form input with question and answer and now i want to convert value of html tag to array.

My code :

<?php
$re = '#<div[^>]*>(.*?)</div>#s';
$str = '<b>1.Question 1?</b><div class="data-check" style="padding-left:25px;"><input class="data-form-input" type="radio" name="q11111" value="a.)Answer 11">a.)Answer 11</div><div class="data-check" style="padding-left:25px;"><input class="data-form-input" type="radio" name="q11111" value="b.)Answer 12">b.)Answer 12</div>';
$result = [];
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the entire match result
foreach($matches as $match){
    $result[] = $match[1];
}

print_r($result);

Current ouput is:

Array
(
    [0] => <input class="data-form-input" type="radio" name="q11111" value="a.)Answer 11">a.)Answer 11
    [1] => <input class="data-form-input" type="radio" name="q11111" value="b.)Answer 12">b.)Answer 12
)

How can i get desired result:

 Array
    (
    [0]: Question 1?
    [1]: Answer 11
    [2]: Answer 12
    )

Thank you

>Solution :

You can try with this code to get your desired output:

<?php
$re_question = '#<b>\d+\.(.*?)</b>#s';
$re_answer = '#<input[^>]* value="([a-z]\.\)(.*?)")>#s';

$str = '<b>1.Question 1?</b><div class="data-check" style="padding-left:25px;"><input class="data-form-input" type="radio" name="q11111" value="a.)Answer 11">a.)Answer 11</div><div class="data-check" style="padding-left:25px;"><input class="data-form-input" type="radio" name="q11111" value="b.)Answer 12">b.)Answer 12</div>';

$question = '';
$answers = [];

//question
preg_match_all($re_question, $str, $matches_question, PREG_SET_ORDER, 0);
if (count($matches_question) > 0) {
    $question = $matches_question[0][1];
}

//answers
preg_match_all($re_answer, $str, $matches_answer, PREG_SET_ORDER, 0);
foreach($matches_answer as $match){
    $answers[] = $match[2];
}

// Combine the question and answers
$result = array_merge([$question], $answers);

print_r($result);
?>

Result:

Array ( [0] => Question 1? [1] => Answer 11 [2] => Answer 12 )

Leave a Reply