简体   繁体   中英

How would I preg_replace the following?

I've got this snippet of code that I will be replacing in various places and I was wondering how would I write the pattern to preg_replace it? Thanks!

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

I'd like to replace it with:

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

If you want to totally replace it, and the code is constant, use str_replace() . If the actual string varies somewhat, do NOT use regexes, as they really don't mix well with XML/HTML or SGML, use a parser ( DOMDocument for instance, with an XPath query and some nodem manipulations).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM