jkushner jkushner - 1 year ago 88
Perl Question

Preserving cetain entities from being encoded algorithm

I have a string that gets parsed through the function

. I need to preserve double-quotes and single-quotes from being encoded so I tried replacing these characters with a flag and then after the encoding function call we replace the flags back with the double and single quote characters, un encoded

Here's my strategy:

// this is a value in the database
my $comment = "<br/>Test<br/>[url=#|onclick="printcoupon('3569')"]test comment[/url]";
$comment =~ s/"/[dq]/g;
$comment =~ s/'/[sq]/g;
$comment = encode_entities($comment);
if(index($comment,"onclick") != -1){
my $start = index($comment,"onclick=");
my $length = index($comment,"\"]");
my $newStr = substr($comment,$start,$length-$start+1);
$comment =~ s!\[url=(.+?)\](.+?)\[\/url\]!<a href="#" style="text-decoration:none;color:#336699" $newStr>$2</a>!g;
} else {
$comment =~ s!\[url=(.+?)\](.+?)\[\/url\]!<a href="$1" style="text-decoration:none;color:#336699">$2</a>!g;
$comment =~ s/\[dq\]/"/g;
$comment =~ s/\[sq\]/'/g;

This code does not work, but its my strategy. Without these replacement calls, the end result is:

<a href="#" style="text-decoration:none;color:#336699" onclick=&quot;printcoupon(&#39;3569&#39;)>test comment</a>

When it should be

<a href="#" style="text-decoration:none;color:#336699" onclick="printcoupon('3569')">test comment</a>

Also, you can see that the end double quotes for the printcoupon function text call do not exist

I need help past this point as i am still a very new perl user


$comment =~ s/&quot;/"/g;
$comment =~ s/&#39;/'/g;

Seems to work but it still does not have an end double quote

Answer Source

It is possible to add the character into the translation table (char2entity hash).

use HTML::Entities;
$HTML::Entities::char2entity{'\''} = '\'';
$HTML::Entities::char2entity{'"'} = '"';

my $comment = qq(<br/>Test<br/>[url=#|onclick="printcoupon('3569')"]test comment[/url]);
$comment  =  HTML::Entities::encode_entities( $comment);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download