How do I encode special characters into their HTML character entity representation?

Some characters have special meanings in HTML, for example, the less-than symbol < and the greater-than symbol >. If you want these characters to be displayed in your browser you need to use the HTML encoding for them. For example, instead of < you use the HTML character entity reference &lt; .

Solution 1

The module HTML::Entities provides a simple way of encoding (and decoding) a string:

    use strict;
    use warnings;
    use HTML::Entities;

    my $string = 'One < Two';

    print "$string\n";

    exit 0;

This program produces the following output:

    One &lt; Two

The encode_entities() routine replaces characters in your string that should be displayed as character entities with their entity representation.

See also

    perldoc HTML::Entities
    HTML::Entities discussed at
    HTML 4 Character Entities
Revision: 1.4 [Top]