Home > Net >  preg_replace find result like Regex
preg_replace find result like Regex

Time:08-28

I have below preg_replace code which looks for <h2> tags and replaces it with $replace_quary, my problem is when there is an HTML tag between <h2>[here]</h2>, it can't do the preg_replace, How can I solve this issue? is there any way I could pass the <h2> with text between, and with preg_replace and regex to find a result that like it? (I pass <h2>Information</h2> and code finde <h3><img src="https://example.com/images/Avatarify-AI-Face-Animator-2.jpg" /> Information' )

for example for this code:

<h3><img src="https://example.com/images/Avatarify-AI-Face-Animator-2.jpg" />
Information</h3>

My Code:

$content = preg_replace('#<h2(.*?)>*?/('. $text .')/</h2>#i', $replace_quary, $content);

CodePudding user response:

I'm not sure but if you want to remove the HTML from string then you can use this

strip_tags("<h2>hello world.</h2>");

CodePudding user response:

With DOM you can manipulate and create any HTML.

$html = '<div ><h2>[here]<span>another code here</span></h2></div>';

libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

$h2 = $doc->getElementsByTagName('h2')->item(0);

$h3  = $doc->createElement('h3');
$img = $doc->createElement('img');
$img->setAttribute('src', 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png');
$h3->appendChild($img);

$h2->parentNode->replaceChild($h3, $h2);

echo $doc->saveHTML();

prints

<div ><h3><img src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"></h3></div>
  • Related