0

I have been trying for a couple of hours. It's simple text (string). Could someone tell me what is wrong with this syntax. Not working

$finalcontent = preg_replace('/<h2>.*?<\/div><\/div>/', '</h2>$variable</div></div>', $finalcontent);

Thanks in advance.

Moon
  • 4,014
  • 3
  • 30
  • 66
Rich
  • 107
  • 1
  • 13

2 Answers2

1

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>
marcell
  • 1,498
  • 1
  • 10
  • 22
-1

You can't add variable in single quotes, your second parameter should be in double quotes "$variable" , not '$variable'

You can find very good ref for Single vs double quotes here: What is the difference between single-quoted and double-quoted strings in PHP?

cNb
  • 67
  • 1
  • 9
  • Adding double quotes will not fix the issue. – FoulFoot Nov 25 '19 at 00:52
  • Actually it will. Please prove me wrong, of course, there is a typo also in the regex

    should be added instead of

    , but this is the solution
    – cNb Nov 25 '19 at 09:29