Kurt Marshman
Kurt Marshman

Reputation: 215

php String Replace Regardless of Capitalization or Quotes

Is there a way to write a string replace over looking capitalization or quotes instead of writing an array for every possible situation?

str_replace(array('type="text/css"','type=text/css','TYPE="TEXT/CSS"','TYPE=TEXT/CSS'),'',$string);

Upvotes: 1

Views: 82

Answers (2)

hlscalon
hlscalon

Reputation: 7552

You can use DOMDocument to do these kind of things: (thanks for @AlexQuintero for the array of styles)

<?php

$doc = new DOMDocument();

$str[] = '<style type="text/css"></style>';
$str[] = '<style type=text/css></style>';
$str[] = '<style TYPE="TEXT/CSS"></style>';
$str[] = '<style TYPE=TEXT/CSS></style>';

foreach ($str as $myHtml) {

echo "before ", $myHtml, PHP_EOL;

$doc->loadHTML($myHtml, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

removeAttr("style", "type", $doc);

echo "after: ", $doc->saveHtml(), PHP_EOL;

}

function removeAttr($tag, $attr, $doc) {
    $nodeList = $doc->getElementsByTagName($tag);
    for ($nodeIdx = $nodeList->length; --$nodeIdx >= 0; ) {
         $node = $nodeList->item($nodeIdx);
         $node->removeAttribute($attr);
    }
}

Online example

Upvotes: 2

Alex Quintero
Alex Quintero

Reputation: 1179

In this case you could do a case-insensitive regular expresion replacement:

Codepad example

preg_replace('/\s?type=["\']?text\/css["\']?/i', '', $string);

Upvotes: 4

Related Questions