0

In my PHP script, I have str1 (see the following code) coming from another page, but for simplicity I have copied its value in the code.

In the string str1, I want to add str2 just before the div #option_one_div, using simple_html_dom if needed.

How can I do that?

<?php

$str1 = '<div style="padding:25px;">
    <div style="background-color:#d9b2b2;">
        <label>Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah </label>
    </div>
    <div id="option_one_div" style="background-color:#74d4dd;">
        <input style="margin-left:30px; margin-right:30px;" type="radio" name="radio" value="0">
        <input style="margin-left:30px; margin-right:30px;" type="radio" name="radio" value="1">
        <label style="margin-left:25px; margin-right:25px;" for="option_one_div">Label of first group of Radio Buttons</label>
    </div>
    <div id="option_two_div" style="background-color:#36d666;">
        <input style="margin-left:30px; margin-right:30px;" type="radio" name="radio" value="0">
        <input style="margin-left:30px; margin-right:30px;" type="radio" name="radio" value="1">
        <label style="margin-left:25px; margin-right:25px;" for="option_two_div">Label of second group of Radio Buttons</label>
    </div>
</div>';

$str2 = '
    <div style="background-color:#bf5b5b; ">
        <label style="margin-left:25px; margin-right:25px;">Yes</label>
        <label style="margin-left:25px; margin-right:25px;">No</label>
    </div>';

?>

3 Answers 3

3

There probably is a better way to do it, but you could use str_replace

$newstr = str_replace('<div id="option_one_div"', $str2.'<div id="option_one_div"', $str1);

This would remove the part start of the option_one_div, and replace it with $str2 with the thing you removed attached, so it will appear again.

But I believe there must be a smarter / simpler way of doing it.

Sign up to request clarification or add additional context in comments.

Comments

1

If the strings are unchanging, you can insert it before more easily than digging apart the html dom.

$find = '<div id="option_two_div"';
$html = str_replace($find,$str2.$find,$str1);

Comments

0

With simple html do m this will look like:

$html = str_get_html($str1);
$option_one_div = $html->find('#option_one_div', 0);
$option_one_div->outertext = $str2 . $option_one_div;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.