====== Fix or Sanitize HTML ======
Yes: I've found the silver bullet for those of you who are seeking for a function that clean html code or sanitize it, specially if it comes from a cut and paste operation from word.
To the point. This snippet:
select dirty, strip_html(dirty) from dual;
Removes all the HTML tags from the html code. But this one:
select dirty, strip_html(dirty,2) from dual;
Wipes out all the garbage who is in the html code, leaving it --more or less-- "clean". And yes, I am using regular expresions to perform the fixing, so it is easy to move it to java or other programming languages. And without more preamble, here is the code:
create or replace function strip_html(dirty in clob,
to_cvs in number default 0)
return clob is out clob ;
type arr_string is varray (200) of varchar2(64);
entities_search_for arr_string;
entities_replace arr_string;
cont number;
begin
-- to accelerate the issue
if dirty is null then
return dirty;
end if; -- isnull(dirty)
if length( dirty ) = 0 then
return dirty;
end if; -- length(dirty)
entities_search_for := arr_string(
'!',
'#',
'$',
'%',
'&',
'"',
'(',
')',
'*',
'+',
',',
'‐',
'.',
'/',
':',
';',
'<',
'=',
'>',
'?',
'@',
'[',
'\',
']',
'ˆ',
'_',
'`',
'{',
'|',
'}',
'˜',
' ',
'¡',
'¢',
'£',
'¤',
'¥',
'¦',
'§',
'¨',
'©',
'ª',
'«',
'¬',
'',
'®',
'¯',
'°',
'±',
'²',
'³',
'´',
'µ',
'¶',
'·',
'¸',
'¹',
'º',
'»',
'&fr;',
'&fr;',
'&fr;',
'¿',
'À',
'Á',
'Â',
'Ã',
'Ä',
'Å',
'Æ',
'&il;',
'È',
'É',
'Ê',
'Ë',
'Ì',
'Í',
'Î',
'Ï',
'Ð',
'Ñ',
'Ò',
'Ó',
'Ô',
'Õ',
'Ö',
'×',
'Ø',
'Ù',
'Ú',
'Û',
'Ü',
'Ý',
'Þ',
'ß',
'à',
'á',
'â',
'ã',
'ä',
'è',
'é',
'ê',
'&etilde;',
'ë',
'ì',
'í',
'î',
'ĩ',
'ï',
'ò',
'ó',
'ô',
'õ',
'ö',
'ù',
'ú',
'û',
'ũ',
'ü');
entities_replace := arr_string(
'¡',
'º',
'$',
'%',
'&',
'"',
'(',
')',
'*',
'+',
',',
'-',
'.',
'Sol',
'Colon',
'*',
'<',
'=',
'>',
'?',
',',
'*',
'*',
'*',
'*',
'_',
'''',
'*',
'*',
'*',
'''',
' ',
'¡',
'cent',
'L',
'*',
'Y',
'*',
'*',
'.',
'(c)',
'*',
'*',
'!',
'*',
'(r)',
'*',
'*',
'*',
'*',
'*',
'á',
'u',
'*',
'·',
'ç',
'*',
'*',
'*',
'*',
'*',
'*',
'¿',
'È',
'Á',
'Ä',
'Á',
'*',
'*',
'AE',
'*',
'È',
'É',
'*',
'*',
'Ì',
'Í',
'Î',
'*',
'*',
'N',
'Ò',
'Ó',
'Ô',
'O',
'*',
'*',
'O',
'Ù',
'Ú',
'Û',
'*',
'*',
'*',
'*',
'à',
'á',
'â',
'a',
'*',
'è',
'é',
'ê',
'e',
'*',
'ì',
'í',
'î',
'i',
'*',
'ò',
'ó',
'ô',
'o',
'*',
'ù',
'ú',
'û',
'u',
'*');
out := dirty;
-- replace what is enclosed between
out := regexp_replace(out,'','
', 1, 0, 'ni');
out := regexp_replace(out,'<([a-zA-Z0-9-_]*)>\1>','', 1, 0, 'ni');
-- TWEAK: must be replaced by
out := regexp_replace(out,'','
', 1, 0, 'ni');
out := regexp_replace(out,'<([a-zA-Z0-9-_]*)>\1>','', 1, 0, 'ni');
else
-- clean html
-- replace all the stuff that is similar to a carriage return
out := regexp_replace(out, '