我如何preg_replace以下?

时间:2010-07-20 22:29:16

标签: php preg-replace

我有这段代码,我将在不同的地方替换,我想知道如何将模式写入preg_replace它?谢谢!

<div class="leftside item1"> 
     <label for="item1">Item1</label> 
</div>

我想用以下代码替换它:

<div class="leftside item1"> 
     <label for="item1">Item1</label> 
</div>
<div class="rightside item1_select"> 
<select class="item1_select" id="item1_select"> 
    <option value="">Select one</option> 
    <option value="1">1</option> 
    <option value="2">2</option> 
</select>

1 个答案:

答案 0 :(得分:0)

如果您想完全替换它,并且代码是常量,请使用str_replace()。如果实际字符串有所不同,请不要使用正则表达式,因为它们实际上与XML / HTML或SGML不能很好地混合,例如使用解析器(DOMDocument,使用XPath查询和一些nodem操作)。 / p>

$html = '<div class="leftside item1">
     <label for="item1">Item1</label>
</div>
<p>aa</p>
<div class="leftside item1">
     <label for="item1">Item1</label>
</div>';

$d = new DOMDocument();
$d->loadHTML($html);
$add = $d->createDocumentFragment();

$x = new DOMXPath($d);
$list = $x->query("//div[@class='leftside item1']");
if($list->length){
    foreach($list as $divnode){
        $add->appendXML('<div class="rightside item1_select">
          <select class="item1_select" id="item1_select">
            <option value="">Select one</option>
            <option value="1">1</option>
            <option value="2">2</option>
          </select>
        </div>');
        if($divnode->nextSibling instanceof DOMNode){
            $divnode->parentNode->insertBefore($add,$divnode->nextSibling);
        } else {
            $divnode->parentNode->appendChild($add);
        }
    }
}
echo $d->saveHTML();