2013-07-22 55 views
0

以下HTML/CSS是從Hotmail發送的HTML電子郵件......PHP stristr假陽性CDATA

<style><!-- 
.hmmessage P 
{ 
margin:0px; 
padding:0px 
} 
body.hmmessage 
{ 
font-size: 12pt; 
font-family:Calibri 
} 
--></style> 

我只是想從裏面的風格元素讓CSS。有些可能包含HTML註釋,如上面的或CDATA。由於一些奇怪的原因,PHP函數返回一個假陽性CDATA低於上述字符串...

if (stristr($b,'<style')) 
{ 
    $s = explode('<style',$b,2)[1]; 
    $s = explode('>',$s,2)[1]; 

    if (stristr($s,'<![CDATA[')) 
    { 
    $s = explode('<![CDATA[',$s,2)[1]; 
    $s = explode(']]',$s,2)[0]; 
    } 
    else if (stristr($s,'<!--')) 
    { 
    $s = explode('<!--',$s,2)[1]; 
    $s = explode('-->',$s,2)[0]; 
    } 
    else 
    { 
    $s = explode('</style>',$s,2)[0]; 
    } 

回答

2

爲什麼不直接拿DOMDocument

$html = " 
<style><!-- 
.hmmessage P 
{ 
margin:0px; 
padding:0px 
} 
body.hmmessage 
{ 
font-size: 12pt; 
font-family:Calibri 
} 
--></style>"; 


$dom = new DOMDocument(); 
$dom->loadHTML($html); 
$style = $dom->getElementsByTagName('style'); 

// get the content from first style tag 
$css = $style->item(0)->nodeValue; 
// clear the comments and cdata tags 
$css = str_replace(array('<!--', '-->', '<![CDATA[', ']]>', '//<![CDATA[', '//]]>'), '', $css); 
echo $css; 
+0

的工作,謝謝! – John