Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Converting UTF8 to Latin1

by ikegami (Pope)
on Jun 20, 2012 at 17:27 UTC ( #977418=note: print w/ replies, xml ) Need Help??


in reply to Converting UTF8 to Latin1

The iso-latin-1 character set is much smaller than the Unicode character set. Fortunately, HTML provides a mechanism to encode character not present in the used character set.

Option 1 (Works with any encoding):

my $to_entitise = q{<>&"'}; # Unsafe for HTML my $decoded_text = decode('UTF-8', $utf8_text); my $decoded_html = encode_entities($decoded_text, $to_entitise); my $latin1_html = encode('iso-latin-1', $decoded_html, Encode::FB_HTML +CREF);

Option 2 (Leverages our knowledge of iso-latin-1):

my $to_entitise = q{<>&"'} . # Unsafe for HTML q{\x{100}-\x{1FFFFF}}; # Not present in iso-8859-1 my $decoded_text = decode('UTF-8', $utf8_text); my $decoded_html = encode_entities($decoded_text, $to_entitise); my $latin1_html = encode('iso-latin-1', $decoded_html);

Option 3 (Works with any encoding by using HTML entities for more than needed):

my $decoded_text = decode('UTF-8', $utf8_text); my $decoded_html = encode_entities($decoded_text); my $latin1_html = encode('iso-latin-1', $decoded_html);

If your UTF-8 encoded data is HTML rather than text, you can use:

my $to_entitise = q{\x{100}-\x{1FFFFF}}; # Not present in iso-8859-1 my $decoded_html = decode('UTF-8', $utf8_html); $decoded_html = encode_entities($decoded_html, $to_entitise); my $latin1_html = encode('iso-latin-1', $decoded_html);

Common headers and test data:

use charnames qw( :full ); # For \N on older Perls use Encode qw( encode decode ); use HTML::Entities qw( encode_entities ); my $utf8_text = encode('UTF-8', "a\N{U+00E9}\N{U+2660} 1<4"); my $utf8_html = encode('UTF-8', "a\N{U+00E9}\N{U+2660} <b>foo</b>");

Update: Small fixes to bugs found during testing.


Comment on Re: Converting UTF8 to Latin1
Select or Download Code
Reaped: Re^2: Converting UTF8 to Latin1
by NodeReaper (Curate) on Mar 05, 2013 at 08:49 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://977418]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (5)
As of 2014-09-21 12:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (168 votes), past polls