Thread Tags finden
(21 answers)
Opened by Froschpopo at 2008-04-13 18:34
so, hier mal eine Testversion für meinen BBCode-Parser.
Code (perl): (dl
)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 package HTML::BBCode; use strict; use warnings; sub new { my $class = shift; my $self = {}; bless($self, $class); $self->_init(@_); return $self; } sub _init { my $self = shift; my %attr = @_; my %tags = ( b => '<strong>%s</strong>', i => '<span style="font-style:italic">%s</span>', u => '<span style="text-decoration:underline">%s</span>', center => '<div style="text-align:center">%s</div>', img => '<img src="%s" alt="Bild" />', color => '<span style="color:%s">%s</span>', size => '<span style="font-size:%sem">%s</span>' ); my %allowedTags = (); if (ref($attr{allowedTags}) eq 'ARRAY') { $allowedTags{$_} = $tags{$_} for @{$attr{allowedTags}}; } else { %allowedTags = %tags; } $self->{escape_html} = 1 if $attr{escape_html}; $self->{allowedTags} = \%allowedTags; } sub parse { my ($self, $text) = @_; $text = escape_html($text) if $self->{escape_html}; $text =~ s/(?<![\n\r])\n(?![\r\n])/<br \/>/g; $text =~ s/[\n\r]+(.*)[\n\r]+/\n<p>$1<\/p>\n/g; for (keys %{$self->{allowedTags}}) { $text =~ s{ \[$_\](.+?)\[/$_\] } { _replace($self,$_,$1) }egsx; $text =~ s{ \[($_)=([a-zA-Z_0-9\#]+)\](.+?)\[/$_\] } { _replace($self,$1,$2,$3) }egsx; } return $text; } sub _replace { my $self = shift; return sprintf($self->{allowedTags}->{shift(@_)}, @_); } sub escape_html { my $text = shift; $text =~ s/&/&/gso; $text =~ s/</</gso; $text =~ s/>/>/gso; return $text; } 1; Hier die Applikation: Code (perl): (dl
)
1 2 3 4 5 6 7 8 9 10 11 #!/usr/bin/perl use strict; use warnings; use HTML::BBCode; my $bbcode = HTML::BBCode->new(allowedTags => [qw(i size)], escape_html =>1); my $string = "[size=3]Ha<test>llo[/size],\n[i]dies[/i]\n\nist ein\n\n[b]fetter Text[/b].[dd]test[/dd]\n"; print $bbcode->parse($string); Und, was meint ihr? Was fehlt noch oder was würdet ihr besser machen? Meine Todo-Liste: - optionale umwandlung von Urls zu Links - Syntax-Validator in einem externen package - [quote] und [code] (dafür fehlt mir noch ne zündende Idee) - einen Switch für XHTML/HTML - Möglichkeit, einem Tag auch eine id (für javascript, css usw.) mitzugeben. |