如何使用 PHP 编写这个 perl 代码?
$var =~ tr/[A-Za-z,.]/[\000-\077]/;
编辑 007 应该是 077
如何使用 PHP 编写这个 perl 代码?
$var =~ tr/[A-Za-z,.]/[\000-\077]/;
编辑 007 应该是 077
php has the strtr function that uses array key=>value pairs where instances of key in a string are replaced with value. Other than that, like @Rocket said, you can use preg_replace_callback to get your replace value. the matched character is passed in to a function and is replaced with whatever the functions returns.
你可以使用preg_replace_callback
Perl
my $var = 'ABCDEFGHIJKLMNOPQRSTUVWXWZabcdefghijklmnopqrstuvwxyz1234567890,.';
$var =~ tr/[A-Za-z,.]/[\000-\077]/;
print unpack("H*", $var), "\n";
PHP
$string = 'ABCDEFGHIJKLMNOPQRSTUVWXWZabcdefghijklmnopqrstuvwxyz1234567890,.';
$replace = preg_replace_callback("/[A-Za-z,.]/", function ($m) {
$n = 0;
if (ctype_punct($m[0])) {
$m[0] == "," and $n = - 8;
$m[0] == "." and $n = - 7;
} else {
$n = ctype_upper($m[0]) ? 65 : 71;
}
return chr(ord($m[0]) - $n);
}, $string);
print(bin2hex($replace));
两个输出
000102030405060708090a0b0c0d0e0f101112131415161716191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f30313233313233343536373839303435
有人说 PHP 没有等价物tr///
(尽管我现在看到它是 as strtr
)。如果是这样,
$var =~ tr/A-Za-z,./\000-\077/;
可以写成如下替代:
my %encode_map;
my $i = 0;
$encode_map{$_} = chr($i++) for 'A'..'Z', 'a'..'z', ',', '.';
$var =~ s/([A-Za-z,.])/$encode_map{$1}/g;
这应该更容易翻译成 PHP,但不幸的是我不知道 PHP。
(我假设[]
intr///
不应该在那里。)