Извлечение строки стиля из головы с помощью preg_replace и preg_match_all - PullRequest
0 голосов
/ 21 декабря 2011

В php хотите собрать строки стиля из заголовка html и заменить их пробелом. Я пытаюсь использовать preg_match_all и preg_replace, но у меня нет рабочих решений.

$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);

1 Ответ

0 голосов
/ 26 августа 2012

Проблема, которую я вижу, состоит в том, что начало вашего регулярного выражения и окончание находятся в разных строках.Измените ваше правило на:

$styles='';

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

, поскольку модификатор s подразумевает, что точка (.) Захватывает не только «что-нибудь, но не конец строки», но и «концы строки».

...