繁体   English   中英

Perl 正则表达式到 php function

[英]Perl regex to php function

I lack basic understandings of RegEx, however I was tasked in converting this perl snippet into php with preg_replace and I cannot quite figure out how to get it to function properly as I cannot figure out how to properly escape the regex string into a var in php .

sub rssEnc {
    my $DATA=shift;
    my %tr=(
    "'" => '"',
    "" => '"',
    '"' => '"',
    '&' => '&',
    '$' => '$',
    '<' => '&lt;',
    '>' => '&gt;',
    '' => '&#39;'
    );
    $DATA=~s/(&(?!(#\w*|quo|apo|amp|lt|gt);)|["'\<\>\$])/$tr{$1}/g;
    $DATA=~s/[^\x{21}-\x{7E}\s\t\n\r]//g;
return $DATA;
}

您可以使用 preg_replace_callback 之类的东西( https://www.php.net/manual/function.preg-replace-callback.php

它可能看起来像这样:

<?
function rssEnc($data) {
    $tr = array(
        "'" => '&#34;',
        "" => '&#34;',
        '"' => '&quot;',
        '&' => '&amp;',
        '$' => '&#36;',
        '<' => '&lt;',
        '>' => '&gt;',
        '' => '&#39;'
    );

    $data = preg_replace_callback('/(&(?!(#\w*|quo|apo|amp|lt|gt);)|["\'\<\>\$])/m', 
        function($match) use($tr) {return $tr[$match[1]];}, 
        $data);
    $data = preg_replace('/[^\x21-\x7e\s\t\n\r]/', '', $data);
    return $data;
};
?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM