在perl中的html实体中编码特殊字符

时间:2012-01-18 14:55:24

标签: perl html-entities

我有一个字符串,其中可以显示!"&#@等特殊字符。如何转换字符串

str = " Hello "XYZ" this 'is' a test & so *n @."

自动将每个特殊字符与其html实体一起使用,以便我得到:

str = " Hello &quot ;XYZ&quot ; this &#39 ;is&#39 ; a test &amp ; so on @" 

我试过

$str=HTML::Entities::encode_entities($str);

但它完成了部分工作@未转换@

SOLUTION:

1)在你的帮助下(Quentin和vol7ron)我想出了这个解决方案(1)

$HTML::Entities::char2entity{'@'} = '@';
$HTML::Entities::char2entity{'!'} = '!';
$HTML::Entities::char2entity{'#'} = '#';
$HTML::Entities::char2entity{'%'} = '%';
$HTML::Entities::char2entity{'.'} = '.';
$HTML::Entities::char2entity{'*'} = '*';
$str=HTML::Entities::encode_entities($str, q{@"%'.&#*$^!});

2)我找到了一个更短(更好)的解决方案(2)找到它here

$str=HTML::Entities::encode_entities($str, '\W');

'\ W'完成工作

使用解决方案(1)

@ von7ron 您需要指定要翻译为 Quentin 的字符,即使它们位于转换表中。

3 个答案:

答案 0 :(得分:4)

@未被转换,因为它不被视为“特殊字符”。它可以用ASCII表示,在HTML中没有重要意义。

您可以将使用第二个参数转换的字符范围扩展为您正在使用的函数as described in the documentation

答案 1 :(得分:2)

您可以手动将字符添加到转换表(char2entity哈希)。

$HTML::Entities::char2entity{'@'} = '@';

my $str      =  q{ Hello "XYZ" this 'is' a test & so on @};
my $encoded  =  HTML::Entities::encode_entities( $str, q{<>&"'@} );
  1. 以上添加@,将其翻译为&#64;
  2. 然后,您需要指定要翻译的字符,如果您没有使用<>&",那么我添加了@'。请注意,我没有必要将'添加到转换表中,因为默认情况下它已经存在。
  3. 您不需要在char2entity哈希中添加ASCII字符(0-255),因为模块会自动执行此操作。

  4. 注意:设置@的char2entity,作为示例。该模块自动为找不到的ASCII字符(0-255)设置数字实体。但是,您必须将它用于unicode字符。

答案 2 :(得分:-1)

便宜,肮脏,丑陋,但有效:

my %translations;
$translations{'"'}  = '&quot ;';
$translations{'\''} = '&#39 ;';
etc...


sub transform()
{
    my $str = shift;
    foreach my $character (keys(%translations))
    {
        $str =~ s/$character/$translations{$character}/g;
    }
    return $str;
}
相关问题