2011-12-21 39 views
0

在php中想要从html头部收集样式行并用空格替换它们。 我尝试使用preg_match_all和preg_replace,但我没有工作解决方案。从头部提取样式标记行preg_replace和preg_match_all

$myhtml=" 
<title>my title</title> 
<link rel="stylesheet" type="text/css" href="style1.css" /> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" /> 
<link href="style2.css" type="text/css" rel="stylesheet" /> 
<!--[if lt IE 9]> 
    <link href="style3.css" rel="stylesheet" type="text/css" /> 
<![endif]--> 
<meta name="author" content="i'm the author" /> 
<!--[if lt IE 6]> 
    <link href="style4.css" type="text/css" rel="stylesheet"/> 
<![endif]--> 
<style> 
    #body{background-color:#CCC;} 
</style> 
"; 

我期待的结果

$myhtml=" 
<title>my title</title> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" /> 
<meta name="author" content="i'm the author" /> 
"; 

$extracted_styles=" 
<link rel="stylesheet" type="text/css" href="style1.css" /> 
<link href="style2.css" type="text/css" rel="stylesheet" /> 
<!--[if gt IE 8]> 
    <link href="style3.css" rel="stylesheet" type="text/css" /> 
<![endif]--> 
<!--[if lt IE 6]> 
    <link href="style4.css" type="text/css" rel="stylesheet"/> 
<![endif]--> 
<style> 
    #body{background-color:#CCC;} 
</style> 
"; 

的PHP:我稍后再尝试提取条件的CSS第一,链接的rel但已经是第一步这么想的工作

$styles=''; 

//extract conditional css 
preg_match_all('/<!--(.*)-->/i', $myhtml, $matches); 
$styles.=implode(" ",$matches); 
preg_replace('/<!--(.*)-->/i', "", $myhtml); 

回答

0

我看到的问题是,你的正则表达式的开始和结束是在不同的行中。您的规则更改为:

$styles=''; 

//extract conditional css 
preg_match_all('/<!--(.*)-->/is', $myhtml, $matches); 
$styles.=implode(" ",$matches); 
preg_replace('/<!--(.*)-->/is', "", $myhtml); 

为s修正意味着点不仅抓住“什么,但线的两端”,也有“行结束”()。