Solace
Solace

Reputation: 9010

PHP: How to add an HTML string into another HTML string at a specific place?

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>';

?>

Upvotes: 0

Views: 72

Answers (3)

pguardiario
pguardiario

Reputation: 54984

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;

Upvotes: 0

Mooseman
Mooseman

Reputation: 18891

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);

Upvotes: 1

razemauze
razemauze

Reputation: 2676

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.

Upvotes: 3

Related Questions