简体   繁体   English

将JS函数转换为PHP

[英]Translating JS function to PHP

I'm trying to "translate" an JS function into PHP equivalent. 我正在尝试将JS函数“翻译”为等效的PHP。 For the following JS function: 对于以下JS函数:

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: 我在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. 我认为它在urldecode()周围的某个地方失败了。 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'); JS函数的结果,例如dF('8%3Fn%3FAAl%3A%3Ej%3D%3C%3B%3A%3DA%3Ail%40llk%3Aj%3B8%38El%3B%40m','55'); would be 07f799d26b5432592ad8ddc2b306d38e 会是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. 从第一个答案修正后, echo dF('8%3Fn%3FAAl%3A%3Ej%3D%3C%3B%3A%3DA%3Ail%40llk%3Aj%3B8%38El%3B%40m', '55')为空,空白,未打印任何内容。

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. 如果执行substr($ str,3),它将在第三个字母之后获得所有内容,而不仅仅是第三个字母。 I assume that's what charCodeAt(...) in your JS does, utilizes only one letter? 我假设这就是您的JS中的charCodeAt(...),只使用一个字母吗?

To get only one letter, do this: 要只收到一封信,请执行以下操作:

echo $str[$i]; // echos the first character of $str if $i was 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM