I have a string like
string(8234) "<style>.{ margin-bottom:10px; float:left; display: inline-block; width:56%; text-align:left; padding-right:20px; padding-left:20px; } . > p { display: table-cell; height: 150px; vertical-align: middle; }..................</style>.................
I want to remove <style> tag and all its contents.
I have tried

$description = $product_info['description']; // the string with style tag
$text = preg_replace('/<\s*style.+?<\s*\/\s*style.*?>/si', ' ', $description );
echo $text;

but it shows the same string without removing <style> tag.
I have also tried to replace only <style> tag by doing

$text    = str_replace("<style>", "", $description);

but this also doesn't work at all. I am seeing the same string again and again. I have also tried it with DOMParser

 $doc =   new DOMDocument();
 $doc->loadHTML($description);
 $xpath = new DOMXPath($doc);
 foreach ($xpath->query('//style') as $node) {
    $node->parentNode->removeChild($node);
 }
 $text    =    $doc->saveHTML();

but in all cases, output is the same with <style> and its contents

Hi,
you could list the items in the head and body elements and then, if you catch the style child, you remove it. This seems to works fine for me:

<?php

/**
 * Remove tag from DOM.
 * 
 * @see http://php.net/manual/en/domnode.removechild.php
 *      Read the comments about the loops
 * @param  DomDocument $doc
 * @param  string      $tag
 * @param  string      $element
 * @return void
 */
function removeTag(DomDocument $doc, $tag, $element = 'body')
{
    $section = $doc->getElementsByTagName($element)->item(0);
    $tag = $section->getElementsByTagName($tag);

    if($tag->length > 0)
    {
        foreach($tag as $node)
            $data[] = $node;

        foreach($data as $n)
            $section->removeChild($n);
    }

    return ;
}

$file = 'index.html';
$doc  = new DOMDocument();
$doc->loadHTMLFile($file);

removeTag($doc, 'style', 'head');
removeTag($doc, 'style', 'body');

$doc->saveHTMLFile($file);

You need to use a loop because:

You can't remove DOMNodes from a DOMNodeList as you're iterating over them in a foreach loop.

See the documentation for more notes:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.