user740521
user740521

Reputation: 1204

What is the PHP equivalent of this perl regular expression

How can I write this perl code using PHP?

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

edit 007 should have been 077

Upvotes: 2

Views: 625

Answers (3)

Baba
Baba

Reputation: 95111

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

Upvotes: 3

ikegami
ikegami

Reputation: 385849

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

Upvotes: 3

Jonathan Kuhn
Jonathan Kuhn

Reputation: 15301

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.

Upvotes: 4

Related Questions