Page 1 of 1
How to translate tr command in Perl to PHP
Posted: Sat Aug 23, 2003 10:57 am
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..
Posted: Sat Aug 23, 2003 1:45 pm
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";
?>
Posted: Sat Aug 23, 2003 1:50 pm
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.

Posted: Sun Aug 24, 2003 12:06 am
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
Posted: Sun Aug 24, 2003 6:47 am
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_...
