PHP实现JS中的escape函数

有时需要把js的算法翻译成其它语言, escap函数虽然已废弃, 但函数常常出现, 根据MDN的描述,尝试用PHP实现它:
function escape($str, $encoding = "utf-8") {
    $wl = '|^[a-zA-Z0-9\*\+\./@\-_]$|';
    $res = '';
    for($i = 0; $i <mb_strlen($str, $encoding); $i++) {
        $it = mb_substr($str, $i, 1, $encoding);
        if(preg_match($wl, $it)) {
            $res .= $it;
            continue;
        }
        
        $it = mb_convert_encoding($it, "ucs-2", $encoding);
        $code = mb_ord($it, "ucs-2");

        if($code <= 0xff) {
            $res .= "%" . strtoupper(substr(bin2hex($it), 2));
        }
        else {
            $res .= "%u" . strtoupper(bin2hex($it));
        }
    }

    return $res;
}