2014-10-02 46 views
1

有没有一种方法来编写一个字符串替换看大写或引号,而不是为每个可能的情况写一个数组?php字符串替换不论大小写或引号

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

正则表达式更适合这个 – 2014-10-02 18:25:24

回答

4

在这种情况下,你可以做一个区分大小写的正规表示更换:

Codepad example

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

我很欣赏键盘示例。我正试图围绕这个......我还有另一个例子。 if(strpos($ html,''')> 0 || strpos($ html,'')> 0){ $ html = str_replace('','',$ html); } – 2014-10-02 18:52:50

+0

如何在if语句中使用您的示例? – 2014-10-02 18:55:58

+0

写一个正则表达式很简单,在这种类型的替换中,在这里http://www.regexr.com/39k2c,玩它:)你可以使用http://php.net/manual/es/function。 preg-match.php用于“if”语句 – 2014-10-02 19:02:04

2

您可以使用DOMDocument做这类事情:(感谢@AlexQuintero为样式阵列)

<?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

+0

他们说,当你用正则表达式解决问题时,你有两个问题:D。我喜欢你的方法,但是很有效。并欢迎您使用阵列 – 2014-10-02 19:04:35

+0

@ 1nflktd杰出的例子。这回答了我的另一个问题。这是你答案的另一个问题。如果我有几个删除removeAttr(“style”,“type”,$ doc);和removeAttr(“script”,“language”,$ doc);可以有多个组合或最好是有两个功能? – 2014-10-02 19:05:58

+0

@AlexQuintero是的,这就是为什么我不喜欢用它与HTML :) – 2014-10-02 19:09:58