Hi all,

First time poster, but to be honest, I should be able to figure this one out. I just can't.

What I am looking to do is use preg_replace function to insert extra divs within an html string.

The initial string is coming from a database, but it would look something like this...

<div id="thisdiv">
[other content]
<div id="divid" class="class1 class2 targetCLass class3">
[other content]
</div>
</div>

Obviously this is a very simple version of what comes out, but it should be enough to get the idea.

What I am looking to do is to insert <div id="new_div_1"></div> and <div id="new_div_2"></div> as in the next block

<div id="thisdiv">
[other content]
<div id="divid" class="class1 class2 targetCLass class3">
[B]<div id="new_div_1"></div>[/B]
[otyher content that will include divs]
[B]<div id="new_div_2"></div>[/B]
</div>
</div>

I have been doing this using jQuery, but would prefer to do it server side if possible.

Thanks in advance, I am really stuck on this.

    While it's possible to do this with regular expressions, DOM manipulation would be more appropriate. With SimpleXML:

    $node = new simplexmlelement( $html_string );
    $div = $node->xpath( '//div[@id="divid"]' );
    if( sizeof( $div ) > 0 )
    {
      $div[0]->addChild( 'div' )->addAttribute( 'id', 'new_div_1' );
    }
    

    My Xpath query is probably wrong, but just an illustration. One caveat: your HTML would need to be well formed or the XML parser would barf.

    My preference would be jQuery though. It's awesome, Tyrannosaurus Awesome.

      Hi thanks for your reply. I agree jQuery is great. That is how it is working at the moment. I am looking to split test server side DOM manipulation against client side - the jQuery seems to take quite a while, despite being incredibly simple. About 3-4 seconds according to firebug.

      I think the problem that I might have is as you said, the HTML is not guaranteed to be in one format or another, and I am not so hot at doing this server side...

        Shrike wrote:

        My Xpath query is probably wrong, but just an illustration. One caveat: your HTML would need to be well formed or the XML parser would barf.

        The alternative [man]DOM[/man] interface has an extra parser for handling HTML without needing it to be well-formed XML; it still has limitations, of course, but it accepts even "<html><body><p>foo" as legal HTML.

          Write a Reply...