It is better to use DOM
instead of regex
in order to manipulate HTML
.
Using DOM
you can effectively manipulate the HTML
document, with the help of DOMNode::appendChild and DOMDocument::createTextNode you can insert text coming from $variable
after the h2
element.
We get the parent of the h2
element ($doc->getElementsByTagName('h2')->item(0)->parentNode
) and append a child to it, that will be placed after the h2
. This child is a textnode created from the input $variable
($doc->createTextNode($variable)
).
$html = '<div><div><h2>Hi</h2></div></div>';
$variable = 'Hello Stackoverflow';
$doc = new DOMDocument();
$doc->loadHTML($html, LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);
$newTextNode = $doc->createTextNode($variable);
$doc->getElementsByTagName('h2')->item(0)->parentNode->appendChild($newTextNode);
echo $doc->saveHTML();
Results in:
<div><div><h2>Hi</h2>Hello Stackoverflow</div></div>