views:

26

answers:

1

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

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();
Wrikken
I tried using str_replace, but it did not work. Not too sure what I was doing wrong.
hsatterwhite