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

Update: Do two runs of encode entities to encode normal characters first time and your special characters the second time. This may be a little slower than doing one pass but means you don't have to specify exactly what else you need to encode.

my $string = '[I haz square brackets]'; my $unsafe_chars = '[]'; # first pass encodes default set my $pass1= encode_entities( $string ); # second pass encodes speshul chars my $encoded = encode_entities( $pass1, $unsafe_chars );
If you spot any bugs in my solutions, it's because I've deliberately left them in as an exercise for the reader! :-)

Replies are listed 'Best First'.
Re^2: HTML::Entities encode_entities for perlmonks [ ]
by Anonymous Monk on Jun 15, 2013 at 09:03 UTC

    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  [ ]

      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! :-)
      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?