Due to carelessness on my part I had a shed load of html containing suspect characters. The difficulty was having a possible combination of x80-x9F (frowned on by w3c), unicode and html entities (including numeric entities).
The strategy I arrived at was to:
  1. decode any entities present
  2. convert x80-x9F to unicode equivalents
  3. encode 'unsafe' characters

This will ensure, hopefully, consistant html and prevent problems during any future processing.

What do you reckon?

#!/usr/bin/perl use strict; use warnings; use HTML::Entities; my $lookup = get_cp1252_lookup(); my $str = join('', chr(0x93), 'double', chr(0x94), chr(0x201C), 'double', chr(0x201D), '&lsquo;single&rsquo;' ); # "replaces HTML entities... # with the corresponding Unicode character" decode_entities($str); # replaces x80-x9f with unicode equivalant $str =~ s/([\x80-\x9f])/$lookup->{sprintf("%x", ord($1))}/eg; # "replaces unsafe characters... # with their entity representation" encode_entities($str); print "$str\n"; sub get_cp1252_lookup{ open my $fh, '<', 'cp1252_to_unicode.txt' or die "can't open input: $!"; my $lookup; while (<$fh>){ my ($cp1252, $utf8_str, $name) = split /\t/; $cp1252 =~ s/0x//; my $utf8 = $utf8_str =~ / /? '':chr(oct($utf8_str)); $lookup->{$cp1252} = $utf8; } return $lookup; } __END__ output: &ldquo;double&rdquo;&ldquo;double&rdquo;&lsquo;single&rsquo; extract from cp1252_to_unicode.txt: 0x91 0x2018 #LEFT SINGLE QUOTATION MARK 0x92 0x2019 #RIGHT SINGLE QUOTATION MARK 0x93 0x201C #LEFT DOUBLE QUOTATION MARK 0x94 0x201D #RIGHT DOUBLE QUOTATION MARK
Many thanks to all the monks who have helped.
John

In reply to Fixing suspect characters in HTML by wfsp

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.