How to translate tr command in Perl to PHP

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Noom
Forum Newbie
Posts: 2
Joined: Sat Aug 23, 2003 10:57 am

How to translate tr command in Perl to PHP

Post by Noom »

Could anyone please help me translate the following Perl to PHP.

$x = "244550";
$x =~ tr/0-9/ABCDEFGHIJ/;
$x =~ s/(\w)\1/${1}X/g;
print "X = $x";
#Result is "X = CEXFXA"

Any suggestion would be highly appreciated
Noom..
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

I never found that translation operator in php
(afaik) you have to work around by "creating" the second list as a function-call and fetch what ever you want from the first list so it can be used as parameter, e.g.

Code: Select all

<?php
$x = "244550";
$x = preg_replace('/([0-9])/e', 'chr($1 +65)', $x);
echo "X = $x \n";
$x = preg_replace('/(\w)\1/', '${1}X', $x);
echo "X = $x \n";
?>
User avatar
BigE
Site Admin
Posts: 139
Joined: Fri Apr 19, 2002 9:49 am
Location: Missouri, USA
Contact:

Post by BigE »

Not sure if this will work or if it's the best way... but...

Code: Select all

<?php
$x = '244550';
$array_num = array('0','1','2','3','4','5','6','7','8','9');
$array_let = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
for($i = 0; $i < strlen($x); $i++)
{
    if ($i + 1 == strlen($x))
    {
    }
    elseif ($x{$i} == $x{$i + 1})
    {
        $i++;
        $x{$i} = 'X';
    }
}
$x = str_replace($array_num, $array_let, $x);
echo $x,"\n";
?>
It seemed to work for me... so hopefully that helps. :)
Noom
Forum Newbie
Posts: 2
Joined: Sat Aug 23, 2003 10:57 am

Post by Noom »

Can I mix the code like this?

<?php
$x = '244550';
$array_num = array('0','1','2','3','4','5','6','7','8','9');
$array_let = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
$x = str_replace($array_num, $array_let, $x);
$x = preg_replace('/(\w)\1/', '${1}X', $x);
echo $x,"\n";
?>

Thanks a lot for your suggestion.
Noom
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

of course you can.
str_replace only returns a string and preg_replace only takes a string as input.
How this string came into existence doesn't matter to preg_... ;)
Post Reply