Reputation: 9521
I'm trying to "translate" an JS function into PHP equivalent. For the following JS function:
function dF(s,n)
{
n=parseInt(n);
var s1=unescape(s.substr(0,n)+s.substr(n+1,s.length-n-1));
var t='';
for(i=0;i<s1.length;i++)
{
t+=String.fromCharCode(s1.charCodeAt(i)-s.substr(n,1));
}
return(unescape(t));
}
i did this in PHP:
function dF( $s, $n ) {
$n1 = intval( $n );
$s1 = urldecode( substr( $s, 0, $n1 ) . substr( $s, $n1+1, strlen( $s)-$n1-1 ));
$t = '';
for( $i = 0; $i < strlen($s1); $i++ ) {
$t .= unichr(substr($s1, $i) - substr($s, $n1, 1));
}
return urldecode($t);
}
/**
* Return unicode char by its code
*
* @param int $u
* @return char
*/
function unichr($u) {
return mb_convert_encoding('&#' . intval($u) . ';', 'UTF-8', 'HTML-ENTITIES');
}
And it fails somewhere around urldecode()
I persume. What am I doing wrong?
--- More info ---
Result for the JS function, for example dF('8%3Fn%3FAAl%3A%3Ej%3D%3C%3B%3A%3DA%3Ail%40llk%3Aj%3B8%38El%3B%40m','55');
would be 07f799d26b5432592ad8ddc2b306d38e
But I'm not getting this as a result. After fixes from first answer,
echo dF('8%3Fn%3FAAl%3A%3Ej%3D%3C%3B%3A%3DA%3Ail%40llk%3Aj%3B8%38El%3B%40m', '55')
is empty, blank, nothing printed.
Upvotes: 1
Views: 228
Reputation: 2707
Looks to me like this is the culprit:
$t .= unichr(ord( $s1[$i] ) - substr($s, $n1, 1));
// ^ This
If you do substr($str, 3) it gets EVERYTHING after the third letter, not just the third letter. I assume that's what charCodeAt(...) in your JS does, utilizes only one letter?
To get only one letter, do this:
echo $str[$i]; // echos the first character of $str if $i was 0
Upvotes: 5