test action
[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   'nbsp' => ' ',   # should be => "\x{00A0}", but this can lead to problems with
14                    # a non-visible character in csv-exports for example
15 );
16
17 sub strip {
18   my ($class_or_value) = @_;
19
20   my $value = !ref($class_or_value) && (($class_or_value // '') eq 'SL::HTML::Util') ? $_[1] : $class_or_value;
21
22   return '' unless defined $value;
23
24   # Remove HTML comments.
25   $value =~ s{ <!-- .*? --> }{}gx;
26
27   if (!%stripper) {
28     %stripper = ( parser => HTML::Parser->new );
29
30     $stripper{parser}->handler(text => sub { $stripper{text} .= $_[1]; });
31   }
32
33   $stripper{text} = '';
34   $stripper{parser}->parse($value);
35   $stripper{parser}->eof;
36
37   $stripper{text} =~ s{\&([^;]+);}{ $entities{$1} || "\&$1;" }eg;
38
39   return delete $stripper{text};
40 }
41
42 1;
43 __END__
44
45 =pod
46
47 =encoding utf8
48
49 =head1 NAME
50
51 SL::HTML::Util - Utility functions dealing with HTML
52
53 =head1 SYNOPSIS
54
55   my $plain_text = SL::HTML::Util->strip('<h1>Hello World</h1>');
56
57 =head1 FUNCTIONS
58
59 =over 4
60
61 =item C<strip $html_content>
62
63 Removes all HTML elements and tags from C<$html_content> and returns
64 the remaining plain text.
65
66 =back
67
68 =head1 BUGS
69
70 Nothing here yet.
71
72 =head1 AUTHOR
73
74 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
75
76 =cut