in reply to Re: HTML::Entities encode_entities for perlmonks [ ]
in thread HTML::Entities encode_entities for perlmonks [ ]

Nice try

#!/usr/bin/perl -- use strict; use warnings; use HTML::Entities ; my $string = '[< smarto >]'; my $unsafe_chars = '[]'; my $encoded = encode_entities( $string, $unsafe_chars ); print "$string\n$encoded\n"; __END__ [< smarto >] &#91;< smarto >&#93;

The question is what to add encode_entities to also encode  [ ] -- I want what the default encode_entities does plus  [ ]

Replies are listed 'Best First'.
Re^3: HTML::Entities encode_entities for perlmonks [ ]
by space_monk (Chaplain) on Jun 15, 2013 at 13:13 UTC

    Next time be a bit more precise with your question! :-)

    You could simply run a first pass of encode_entities with no params so it would encode the default values, and the second pass with any special characters you also need encoding. I've amended my original answer accordingly.

    If you spot any bugs in my solutions, it's because I've deliberately left them in as an exercise for the reader! :-)
Re^3: HTML::Entities encode_entities for perlmonks [ ]
by trizen (Hermit) on Jun 15, 2013 at 10:10 UTC
    Why not just encode the other characters manually?
    use HTML::Entities ; my $string = '[< smarto >]'; my $unsafe_chars = '[]'; my $encoded = encode_entities($string) =~ s{([\Q$unsafe_chars\E])}{sprintf"&#%d;",ord$1}egr; print "$string\n$encoded\n";

      Why not just encode the other characters manually?

      :) Q: How do I fix this here knife? A: Why not use another knife?