SL::HTML::Util::strip: HTML-Entitäten zurückübersetzen
[kivitendo-erp.git] / SL / HTML / Util.pm
1 package SL::HTML::Util;
2
3 use strict;
4 use warnings;
5
6 use HTML::Parser;
7
8 my %stripper;
9 my %entities = (
10   'lt'  => '<',
11   'gt'  => '>',
12   'amp' => '&',
13 );
14
15 sub strip {
16   my ($class_or_value) = @_;
17
18   my $value = !ref($class_or_value) && (($class_or_value // '') eq 'SL::HTML::Util') ? $_[1] : $class_or_value;
19
20   if (!%stripper) {
21     %stripper = ( parser => HTML::Parser->new );
22
23     $stripper{parser}->handler(text => sub { $stripper{text} .= $_[1]; });
24   }
25
26   $stripper{text} = '';
27   $stripper{parser}->parse($value);
28   $stripper{parser}->eof;
29
30   $stripper{text} =~ s{\&([^;]+);}{ $entities{$1} }eg;
31
32   return delete $stripper{text};
33 }
34
35 1;
36 __END__
37
38 =pod
39
40 =encoding utf8
41
42 =head1 NAME
43
44 SL::HTML::Util - Utility functions dealing with HTML
45
46 =head1 SYNOPSIS
47
48   my $plain_text = SL::HTML::Util->strip('<h1>Hello World</h1>');
49
50 =head1 FUNCTIONS
51
52 =over 4
53
54 =item C<strip $html_content>
55
56 Removes all HTML elements and tags from C<$html_content> and returns
57 the remaining plain text.
58
59 =back
60
61 =head1 BUGS
62
63 Nothing here yet.
64
65 =head1 AUTHOR
66
67 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
68
69 =cut