For this you can use PHP DOM classes / functions.
Start by creating / loading a document:
$d = new DOMDocument();
$d->loadHTML($yourWellFormedHTMLString);
Then you will want to find the node document that you want to modify. You can do this with XPath:
$xpathsearch = new DOMXPath($d);
$nodes = $xpathsearch->query('//div[contains(@class,'main')]');
Then you will need to iterate over the matching nodes and create new nodes inside:
foreach($nodes as $node) {
$newnode = $d->createDocumentFragment();
$newnode->appendXML($yourCodeYouWantToFillIn);
$node->appendChild($newnode);
}
If you don't mind fiddling with the library at an early stage of development, check out CAST (Content-Address Style Templates). This is largely intended to do what you describe, and if nothing else, you could look inside the source to see examples.
(. , , //div[contains(@class,'main')] CSS div.main... . , , , , , xpath , . ids .:)