PHP:如何在特定位置将HTML字符串添加到另一个HTML字符串中


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

在我的PHP脚本中,我有来自另一个页面的str1(请参阅下面的代码),但为了简单起见,我在代码中复制了它的值。

在字符串str1中,我想在div #option_one_div之前添加str2,如果需要,可以使用simple_html_dom

我该怎么做?

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

可能有更好的方法,但您可以使用str_replace

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

这将删除option_one_div的部分开头,并将其替换为带有所删除内容的$str2,这样它将再次出现。

但我相信一定有更聪明/更简单的方法。

如果字符串是不变的,那么可以比挖掘html dom更容易地插入它。

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

使用简单的html do m,这看起来像:

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