到目前为止,我的尝试揭示了我对反向引用以及如何在Perl Regex中正确使用它们的有限理解。我可以将输入文件转换为输出文件,但它仅捕获一行中的一个“style”,并且仅替换该CSS中的一个名称/值对。
我可能是错误的方法,但我想不出更快或更聪明的方法来在Perl中完成这项任务。任何帮助都将不胜感激!
注意:我尝试更改此特定脚本的唯一属性是“高度”,“宽度”和“边框”,因为我们的客户使用工具自动将样式应用于他们使用WYSIWYG风格编辑器拖动的元素。显然,使用正则表达式从许多地方剥离这些属性相当有效,因为您只需让表格单元格按其内容调整大小即可,这看起来很好,但我认为处理问题的更快速的方法就是用“宽度”、“高度”和“边框”属性替换这三个属性,它们的行为大部分与其css对应物相同(除了CSS允许您实际自定义边框的宽度、颜色和样式,但他们仅使用固定的1px,因此我可以添加一个条件来将“solid 1px”替换为“border = 1”。我意识到这些并不完全等效,但对于此应用程序而言,这是一步)。
以下是我目前的内容:
#!/usr/bin/perl
if (!@ARGV[0] || !@ARGV[1])
{
print "Usage: converter.pl [input file] [output file] \n";
exit;
}
open FILE, "<", @ARGV[0] or die $!;
open OUTFILE, ">", @ARGV[1] or die $!;
my $line;
my $guts;
while ( <FILE> ) {
$line = $_ ;
$line =~ /style=\"(.+)\"/;
$guts = $1;
$guts =~ /([a-zA-Z]+)\:([a-zA-Z0-9]+)\;/;
$name = $1;
$value = $2;
$guts = $name."=".$value;
$line =~ s/style=\"(.+)\"/$guts/g;
print OUTFILE $line ;
}
exit;
注意:这不是作业,我也不是让你替我完成工作。这只是一个内部工具,可以加快我们处理传入的HTML以便于在PDF转换器中正常工作的过程。
更新:
对于那些感兴趣的人,我已经得到了一个初始版本。这个版本只替换宽度和高度,我们暂时放弃了边框属性。但如果有人想看看我们是如何做到的,请看一下...
#!/usr/bin/perl
## NOTES ##
# This script was made to simply replace style attributes with their name/value pair equivalents as attributes.
# It was designed to replace width and height attributes on a metric buttload of table elements from client data we got.
# As such, it's not really designed to handle more than that, and only strips the unit "PX" from the values.
# All of these can be modified in the second foreach loop, which checks for height and width.
if (!@ARGV[0] || !@ARGV[1])
{
print "Usage: quickvert.pl [input file] [output file] \n";
exit;
}
open FILE, "<", @ARGV[0] or die $!;
open OUTFILE, ">", @ARGV[1] or die $!;
my $line;
my $guts;
my $count = 1;
while ( <FILE> ) {
$line = $_ ;
my (@match) = $line =~ /style=\"(.+?)\"/g;
my $guts;
my $newguts;
foreach (@match) {
#print $_ ."\n";
$guts = $_;
$guts =~ /([a-zA-Z]+)\:([a-zA-Z0-9]+)\;/;
$newguts = "";
foreach my $style (split(/;/,$guts)) {
my ($name, $value) = split(/:/,$style);
$value =~ s/px//g;
if ( $name =~ m/height/g || $name =~ m/width/g ) {
$newguts .= "$name='$value' ";
} else {
$newguts .= "";
}
}
#print "replacing $guts with $newguts on line $count \n";
$line =~ s/style=\"$guts\"/$newguts/i;
}
#print $newguts;
print OUTFILE $line ;
$count++;
}
exit;