Home: Perl Programming Help: Beginner:
Replace special characters



mmcw
User

Dec 4, 2000, 8:43 AM


Views: 463
Replace special characters

I there a simple way to replace special characters. I now use something like this:

sub replace_data {

my $text = shift;

$text =~ s/\"/\&quot\;/g;
$text =~ s/\&/\&amp\;/g;
$text =~ s/\'/\&acute\;/g;
$text =~ s/\/\&acute\;/g;
$text =~ s/\|/\&brvbar\;/g;
$text =~ s/\</\&lt\;/g;
$text =~ s/\>/\&gt\;/g;
$text =~ s//\&auml\;/g;
$text =~ s//\&ouml\;/g;
$text =~ s//\&uuml\;/g;
$text =~ s//\&Auml\;/g;
$text =~ s//\&Ouml\;/g;
$text =~ s//\&Uuml\;/g;
$text =~ s//\&szlig\;/g;

return $text;
}

But there are a lot more of those special characters!! I there a simple way to replace all those special characters??


perlplexer
Deleted

Dec 3, 2000, 10:09 PM


Views: 463
Re: Replace special characters

1) If you know ASCII codes for those characters then
$crap =~ s/([\x09\x78-\xF0])/\\$1;/g;

2) If not
@junk = qw/ /;
$junk = join "|", @junk;
$crap =~ s/($junk)/\\$1;/g;

you may want to look up quotemeta() function as well (perldoc -f quotemeta)

perlplexer


mmcw
User

Dec 3, 2000, 10:20 PM


Views: 463
Re: Replace special characters

All characters has bee converted to HTML.
& has to be &..amp; etc. (erase the ..)


perlplexer
Deleted

Dec 4, 2000, 11:15 AM


Views: 463
Re: Replace special characters

%convert = ("&" => "&", "aha" => "doh", "crap" => "parc");

$match = join "|", keys %convert;

$crap =~ s/($match)/$convert{$1}/ige;

perlplexer