2

我正在尝试将以下 javascript 函数转换为 PHP:

function lzw_decode(s) {
    var dict = {};
    var data = (s + "").split("");
    var currChar = data[0];
    var oldPhrase = currChar;
    var out = [currChar];
    var code = 256;
    var phrase;
    debugger;
    for (var i=1; i<data.length; i++) {
        var currCode = data[i].charCodeAt(0);
        if (currCode < 256) {
            phrase = data[i];
        }
        else {
           phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
        }
        out.push(phrase);
        currChar = phrase.charAt(0);
        dict[code] = oldPhrase + currChar;
        code++;
        oldPhrase = phrase;
    }
    return out.join("");
}

这是我转换后的代码:

function uniord($c) {

    $a = unpack('N', mb_convert_encoding($c, 'UCS-4BE', 'UTF-8'));
    return($a[1]);

}

function mb_str_split( $string ) { 
    # Split at all position not after the start: ^ 
    # and not before the end: $ 
    return preg_split('/(?<!^)(?!$)/u', $string ); 
}

function decode($s){

    $dict = array();

    $data = mb_str_split($s);

    // print_r($data);


    $currChar = $data[0];
    // echo $currChar;
    // exit();
    $oldPhrase = $currChar;

    $out = array();
    $out[] = $currChar;
    $code = 256;
    $phrase;

    for ($i=1; $i < count($data); $i++) { 

        $currCode = uniord($data[$i]);

        if($currCode < 256){
            $phrase = $data[$i];
        }else{
            $phrase = isset($dict[$currCode]) ? $dict[$currCode] : ($oldPhrase . $currChar);
        }

        $out[] = $phrase;


        $currChar = mb_substr($phrase, 0, 1);
        $dict[$code] = $oldPhrase . $currChar;

        $code++;
        $oldPhrase = $phrase;

    }

    return implode("", $out);

}

虽然此函数适用于某些 LZW 编码的字符串,但如果您使用足够长的字符串,您会发现它不是 100% 准确的。我的猜测是多字节字符串的问题和我的粗心。有人有想法么?

4

0 回答 0