/    Sign up×
Community /Pin to ProfileBookmark

Translating Python into PHP – Need help finishing

Hi guys,

Need some help translating some Python to PHP. There is the Python snippet as well as a non working version of a PHP conversion. Any help on this would be greatly appreciated.

Python

[CODE]def bchr(ord):
if not (32 < ord < 126):
return “\” + oct(ord).lstrip(‘0’).rjust(3, ‘0’)
elif ord == 92:
return r’\’
else:
return chr(ord)

def encode(data):
return ”.join([bchr(ord(x)) for x in data])

def decode(data):
diter = iter(data)
output = []
next = diter.next
for x in diter:
if x == “\”:
try:
y = next()
except StopIteration:
raise ValueError, “incomplete backslash sequence”
if y == “\”:
pass
elif y.isdigit():
try:
os = ”.join((y, next(), next()))
except StopIteration:
raise ValueError, “incomplete backslash sequence”
try:
x = chr(int(os, base = 8))
except ValueError:
raise ValueError, “invalid bytea octal sequence ‘%s'” %(os,)
else:
raise ValueError, “invalid backslash follow ‘%s'” %(y,)
output.append(x)
return ”.join(output)[/CODE]

PHP

[CODE]public function bchr($ord)
{
if (!((32<$ord)&&($ord<126)))
{
$result = “\\”. str_pad(ltrim(decoct($ord),0),3,0, STR_PAD_LEFT);
Mage::log(‘1=’.$result);
return $result;
}
elseif ($ord==92)
{
$result = ‘\\’;
Mage::log(‘2=’.$result);
return $result;
}
else
{
$result = chr($ord);
Mage::log(‘3=’.$result);
return $result;
}
}

public function encode($data)
{
$joined = ”;
$pregData = preg_split(‘//’, $data, -1, PREG_SPLIT_NO_EMPTY);
foreach ($pregData as $x)
{
$ord = ord($x);
Mage::log(‘x=’.$x);
Mage::log(‘ord=’.$ord);
$joined .= $this->bchr($ord);
}

return $joined;
}

public function decode($data)
{
$pregData = preg_split(‘//’, $data, -1, PREG_SPLIT_NO_EMPTY);
$output = ”;
foreach ($pregData as $x)
{
if ($x == ‘\\’)
{
$y = next($pregData);
//Mage::log($y);
if ($y == ‘\\’)
{
continue;
}
elseif (is_int($y))
{
$os = $y.next($pregData).next($pregData);
$x = chr(intval($os, 8));
Mage::log($x);
}
else
{
//Mage::throwException(‘Invalid Backslash Follow $y’);
}
}
$output .= $x;
}

return $output;
}[/CODE]

to post a comment
PHP

0Be the first to comment 😎

×

Success!

Help @elfling spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.2,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,
)...