4

How can I get

my $name = 'John "FOO" Rambo';

expanded in

<span title=\"The great and mighty $name\"

To something like

<span title=\"The great and mighty John \"FOO\" Rambo\"</span>

rather than

<span title=\"The great and mighty John "FOO" Rambo\"

So that my html tag is not corrupted when generating a page and the name contains " ?

serenesat
  • 4,611
  • 10
  • 37
  • 53
Zloj
  • 2,235
  • 2
  • 18
  • 28

2 Answers2

1

The proper HTML would be the following:

<span title="The great and mighty John &quot;FOO&quot; Rambo">...</span>

You can obtain it using the following:

use HTML::Entities qw( encode_entities );

my $html = '<span title="' . encode_entities("The great and mighty $name") . '">...</span>';
   -or-
my $html = '<span title="The great and mighty ' . encode_entities($name) . '">...</span>';

You should probably be using a template system. Were you to use Template-Toolkit, the template would be

<span title="The great and mighty [% name | html %]">...</span>
ThisSuitIsBlackNot
  • 23,492
  • 9
  • 63
  • 110
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • And this whole time I've been manually escaping HTML entities before passing them to TT. I should have known that would be built in...time to read some docs. – ThisSuitIsBlackNot Oct 06 '15 at 14:45
  • 1
    @ThisSuitIsBlackNot, It's a builtin FILTER. It doesn't escape single-quotes, so you need to use double-quotes for your attribute value delimiters. – ikegami Oct 06 '15 at 15:00
-2

The correct HTML would be produced by using &quot;

my $name = 'John "FOO" Rambo';
$name =~ s/"/&quot;/g;
my $html = "<span title=\"The great and mighty $name\"/>";
print $html ."\n";

For clarify on your original question:

You can use simple regular expression to substitute quotes. Example:

my $name = 'John "FOO" Rambo';
$name =~ s/"/\\"/g;
my $html = "<span title=\"The great and mighty $name\"/>";
print $html ."\n";

This

$name =~ s/"/\\"/g;

simply says replace all " with \" (but since \ is special character is needs to be escaped as \\".

the g means globally, i.e. all occurences within the string.

(i.e. if you run only $name =~ s/"/\\"/; then $name would be John \"FOO" Rambo, but with g it is John \"FOO\" Rambo)

But this won't produce a valid HTML

rbm
  • 3,243
  • 2
  • 17
  • 28