2014-10-02 51 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