1

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);
Kurt Marshman
  • 215
  • 2
  • 16

2 Answers2

4

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

Codepad example

preg_replace('/\s?type=["\']?text\/css["\']?/i', '', $string);
Alex Quintero
  • 1,160
  • 10
  • 21
  • I appreciate the Codepad example. I am trying to wrap my head around this...I have another example. if(strpos($html,'')> 0 || strpos($html,'')> 0){ $html = str_replace('','',$html); } – Kurt Marshman Oct 02 '14 at 18:52
  • How would I use your example in the if statement? – Kurt Marshman Oct 02 '14 at 18:55
  • Write a regular expresion is quite simple, in this type of replaces, here http://www.regexr.com/39k2c, play with it :) You can use http://php.net/manual/es/function.preg-match.php for an `if` statement – Alex Quintero Oct 02 '14 at 19:02
  • 1
    I never knew regexr existed. Thnak you for the link. – Kurt Marshman Oct 02 '14 at 19:43
2

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

hlscalon
  • 7,304
  • 4
  • 33
  • 40
  • They say that when you solve a problem with regex then you have two problems :D. I like your approach, is verbose but effective. And you're welcome with the use of the array – Alex Quintero Oct 02 '14 at 19:04
  • @1nflktd Outstanding example. That answers another one of my questions. Here is another question building on your answer. What if I had several to remove removeAttr("style", "type", $doc); and removeAttr("script", "language", $doc); could multiple be incorporated or best bet to have two functions? – Kurt Marshman Oct 02 '14 at 19:05
  • @AlexQuintero yep, that's why I don't like to use it with html :) – hlscalon Oct 02 '14 at 19:09
  • 1
    http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – Alex Quintero Oct 02 '14 at 19:13