Here we go. I'm making several assumptions that will only hold because my designer uses a certain style:
- Everything is a div
- I only want to see text styles, so I'll ignore anything that doesn't seem text-related
Not my best stuff, but it works for the majority of my styles. Had to manually edit a few tags, such as ul, ol, li, and remove 'body'.
#!/usr/bin/perl
use warnings;
use strict;
my $css;
open(FILE, '<', 'styles.css') or die();
while (<FILE>) { $css .= $_; }
close(FILE);
my (@css) = $css =~ m/^([a-zA-Z.#][^\n\r]+{.+?})/gmxs;
my @text_css = grep { /\s(h[1-5]|span|font|color|p|a|ol|ul)\b/ } @css;
foreach my $css(@text_css) {
my ($selector_text) = $css =~ /^([^{]*){/;
my (@selector) = split(/[\s{]/,(split(/[\n\r]+/,$selector_text))[0]);
@selector = grep { !/{/ } @selector;
my $start_html = '';
my $middle_html = join(" ",@selector);
my $end_html = '';
my $result = '';
for (my $i=0; $i< scalar(@selector); $i++) {
$selector[$i] =~ s/:[-\w]+//g;
if (substr($selector[$i],0,1) eq '#') {
$selector[$i] =~ s/^#//g;
$start_html .= qq(<div id="$selector[$i]">);
$end_html = "</div>" . $end_html;
}
elsif (substr($selector[$i],0,1) eq '.') {
$selector[$i] =~ s/^\.//g;
$start_html .= qq(<div class="$selector[$i]">);
$end_html = "</div>" . $end_html;
}
else {
# we have a tag, possibly with an id/class
my($tag,$extra,$type);
if ($selector[$i] =~ m/\./) {
($tag,$extra) = split('.', $selector[$i]);
$extra =~ s/^\.//g;
$type = 'class';
}
elsif ($selector[$i] =~ m/#/) {
($tag,$extra) = split('#', $selector[$i]);
$extra =~ s/^#//g;
$type = 'id';
}
else {
$tag = $selector[$i];
}
if ($extra and $type) {
$start_html .= qq(<$tag $type="$extra">);
}
else {
$start_html .= qq(<$tag>);
}
$end_html = "</$tag>" . $end_html;
}
# is this the last one?
if ($i == scalar(@selector) - 1) {
$result = $start_html . $middle_html . $end_html;
}
print "<div>$result</div>\n" if ($result);
}
}