2

How can I write this perl code using PHP?

$var =~ tr/[A-Za-z,.]/[\000-\077]/;

edit 007 should have been 077

user740521
  • 1,175
  • 4
  • 12
  • 25
  • 2
    PHP doesn't have fancy translations like Perl does. You're probably going to want to use [`preg_replace_callback`](http://php.net/preg_replace_callback). – gen_Eric Oct 31 '12 at 18:29
  • 2
    why don't you post your attempt so that people can help you improve it? – Ali Oct 31 '12 at 18:30
  • What is the Perl equivalent of this Perl expression? Your search list has 56 characters and you replacement list has 66. – mob Oct 31 '12 at 19:42
  • @mob, 54 and 64, actually. The extras in the replacement list are ignored, so it's basically `tr/[A-Za-z,.]/[\000-\065]/`. – ikegami Oct 31 '12 at 20:56
  • Don't the `[` and `]` count? By my reckoning the replacement list is `[\000-\066`. But the point is that it's almost surely not what the OP intended. – mob Oct 31 '12 at 21:18
  • @mob, oh yeah, those `[]` aren't suppose to be there. – ikegami Oct 31 '12 at 21:33

3 Answers3

4

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.

Jonathan Kuhn
  • 15,279
  • 3
  • 32
  • 43
3

You can use preg_replace_callback Perl

my $var = 'ABCDEFGHIJKLMNOPQRSTUVWXWZabcdefghijklmnopqrstuvwxyz1234567890,.';
$var =~ tr/[A-Za-z,.]/[\000-\077]/;
print unpack("H*", $var), "\n";

PERL Live Demo

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));

PHP Live Demo

Both Output

000102030405060708090a0b0c0d0e0f101112131415161716191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f30313233313233343536373839303435
Baba
  • 94,024
  • 28
  • 166
  • 217
3

Someone said PHP doesn't have an equivalent of tr/// (though I now see that it does as strtr). If so,

$var =~ tr/A-Za-z,./\000-\077/;

can be written as a substitution as follows:

my %encode_map;
my $i = 0;
$encode_map{$_} = chr($i++) for 'A'..'Z', 'a'..'z', ',', '.';

$var =~ s/([A-Za-z,.])/$encode_map{$1}/g;

This should be easier to translate to PHP, but I unfortunately don't know PHP.

(I'm assuming the [] in the tr/// aren't supposed to be there.)

ikegami
  • 367,544
  • 15
  • 269
  • 518