Skip to content

Instantly share code, notes, and snippets.

@ahomu
Created January 28, 2011 05:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahomu/799857 to your computer and use it in GitHub Desktop.
Save ahomu/799857 to your computer and use it in GitHub Desktop.
head内のCSSをインラインに置き換える ゆるふわPHP
<?php
/**
* まだ途中. とりあえずCSSをセレクタとプロパティに大ざっぱに分割したとこ
*/
error_reporting(E_ALL);
ini_set('display_errors', 1);
$resourse = <<< DOC_END
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8" />
<title>実験</title>
<style type="text/css">
body {
font-size: 1.3em;
}
h2.sub,
h1#title {
background-color: red;
padding : 5px 3px;
}
</style>
</head>
<body>
<h1 id="title">タイトル</h1>
<h2 class="sub">見出し</h2>
</body>
</html>
DOC_END;
if ( preg_match('/<style\s+type="text\/css">(.*)<\/style>/s', $resourse, $matches) ) {
$styleElem = $matches[0];
$resourse = str_replace($styleElem, '', $resourse);
// ゴミ掃除 ( コメント & 2つ以上連続した空白 & 改行 )
$styleBody = preg_replace('/\/\*(.*?)\*\//s', '',
preg_replace('/( {2,}|\t)/', ' ',
str_replace(array("\r", "\n"), '', $matches[1])
)
);
// セレクタとプロパティをキャプチャするregex
// http://www.w3.org/TR/css3-selectors/#w3cselgrammar
$regex = '/'.
'([a-zA-Z0-9="^*$!+~>|#:.,_\-\[\]\(\)\s]+)'. // CSS selector
'\s*\{\s*'. // {
'([a-zA-Z0-9%#:;.,_\-\(\)\s]+)'. // CSS property
'\s*\}\s*'. // }
'/';
if ( preg_match_all($regex, $styleBody, $matches) ) {
$selectors = $matches[1];
$properties = $matches[2];
if ( count($selectors) !== count($properties) ) {
die('can not combine');
}
$collection = array_combine($selectors, $properties);
var_dump($collection);
print $resourse;
}
} else {
die('style element is not exist');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment