HTML::Util: Tests, und Bugfixes für ein paar Randbedingungen
[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   return '' unless defined $value;
21
22   # Remove HTML comments.
23   $value =~ s{ <!-- .*? --> }{}gx;
24
25   if (!%stripper) {
26     %stripper = ( parser => HTML::Parser->new );
27
28     $stripper{parser}->handler(text => sub { $stripper{text} .= $_[1]; });
29   }
30
31   $stripper{text} = '';
32   $stripper{parser}->parse($value);
33   $stripper{parser}->eof;
34
35   $stripper{text} =~ s{\&([^;]+);}{ $entities{$1} || "\&$1;" }eg;
36
37   return delete $stripper{text};
38 }
39
40 1;
41 __END__
42
43 =pod
44
45 =encoding utf8
46
47 =head1 NAME
48
49 SL::HTML::Util - Utility functions dealing with HTML
50
51 =head1 SYNOPSIS
52
53   my $plain_text = SL::HTML::Util->strip('<h1>Hello World</h1>');
54
55 =head1 FUNCTIONS
56
57 =over 4
58
59 =item C<strip $html_content>
60
61 Removes all HTML elements and tags from C<$html_content> and returns
62 the remaining plain text.
63
64 =back
65
66 =head1 BUGS
67
68 Nothing here yet.
69
70 =head1 AUTHOR
71
72 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
73
74 =cut