Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading