使用 str_replace 中的函数

Using a function in str_replace

我正在尝试手动将一些 Javascript 转换为 PHP。我要转换的脚本是:

if (s)
    r += "\"" + s;
else
    r += "\"";

r += "\\\"+" + gv + "._+" + n.toString(16).replace(/[0-9a-f]/gi, function(c) {
    return gv + "." + b[parseInt(c, 16)] + "+"});
s = "";

我想出的是:

if ($s) {
    $r = $r . "\"" . $s;
} else {
    $r = $r . "\"";
}
$r = $r . "\\\"+" . str_replace([0-7],function($c, $GlobalVar, $b){
        return $GlobalVar.".".$b[$c]."+";
    },ord($n));

但我得到:

The localhost page isn’t working
localhost is currently unable to handle this request.
HTTP ERROR 500

我假设在 str_replace 中使用一个函数会破坏脚本,但如果我删除它,我不知道我是否能找到与 Javascript 代码相同的功能。感谢任何帮助。

Php 日志:

[Thu Aug 25 12:46:43.157926 2016] [:error] [pid 5864] [client 127.0.0.1:53936] PHP Catchable fatal error: Object of class Closure could not be converted to string in /var/www/html/html/test.php

错误很简单,你只需要阅读错误信息:

 Object of class Closure could not be converted to string

您传递给函数的变量不是字符串。

并且您不能使用与 Javascript 相同的语法,因为它与 PHP 不同,您不能使用 "literal conversion"

php 函数的作用与 js 函数的作用完全不同。

假设 gvb 的值相同,并且 n 是一个整数,最后一行应该是

$r = $r . "\\\"+$gv._+" . implode('', array_map(function($c) use ($b, $gv) {return $gv . "." . $b[hexdec($c)] . "+";}, str_split(dechex($n))));

或为了便于阅读而格式化:

$r = $r . "\\\"+$gv._+" 
    . implode(
        '', 
        array_map(
            function($c) use ($b, $gv) {
                return $gv . "." . $b[hexdec($c)] . "+";
            }, 
            str_split(dechex($n))
        )
    );