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

时间:2014-08-26 14:09:58

标签: php html simple-html-dom

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

在字符串str1中,我想在div str2之前添加#option_one_div,如果需要,使用 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>';

?>

3 个答案:

答案 0 :(得分:3)

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

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

这将删除option_one_div的part start,并将$ str2替换为你删除的东西,因此它会再次出现。

但我相信必须有更聪明/更简单的方法。

答案 1 :(得分:1)

如果字符串不变,你可以比插入html dom更容易插入它。

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

答案 2 :(得分:0)

使用简单的html,这将是:

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