Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
tree: 2977e49e74
Fetching contributors…

Cannot retrieve contributors at this time

42 lines (34 sloc) 1.249 kb
use v6;
module Text::Escape;
sub escape($str as Str, Str $how) is export {
given $how.lc {
when 'none' { $str }
when 'html' { escape_html($str) }
when 'uri' | 'url' { escape_uri($str) }
default { fail "Don't know how to escape format $how yet" }
}
}
sub escape_html(Str $str) returns Str is export {
return $str unless $str ~~ /<[&<>"']>/;
$str.subst(q{&}, q{&amp;}, :g)\
.subst(q{<}, q{&lt;}, :g)\
.subst(q{>}, q{&gt;}, :g)\
.subst(q{"}, q{&quot;}, :g)\
.subst(q{'}, q{&#39;}, :g);
}
sub escape_uri(Str $str) returns Str is export {
return $str unless $str ~~ /<-[a..z A..Z 0..9 \-_.!~*'()]>/;
my Str $allowed = 'abcdefghijklmnopqrstuvwxyz'
~ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
~ '0123456789'
~ q{-_.!~*'()};
return [~] $str.comb.map(-> $char {
given $char {
when q{ } { q{+} }
when defined $allowed.index($char) { $char }
# TODO: each char should be UTF-8 encoded, then its bytes %-encoded
default { q{%} ~ ord($char).fmt('%x') }
}
});
}
# vim:ft=perl6
Jump to Line
Something went wrong with that request. Please try again.