如何缩短字符串?

时间:2017-11-08 11:23:38

标签: php string

我想在我的会员链接中添加一个谷歌adwords ID作为subid。问题是我的联盟计划不允许这么长的子ID。有没有办法缩短它?

例如,我从谷歌获得的ID如下所示:

jdfJHGsds57JHJsdkjjkskdfj324GFGHJ3334GHJ

所以我的链接看起来像这样:

www.mysite.com/?affofferid=jdfJHGsds57JHJsdkjjkskdfj324GFGHJ3334GHJ

我想通过编码或任何其他方法缩短谷歌ID。我怎么能这样做?

我希望以后可以手动将ID转换回原来的。

1 个答案:

答案 0 :(得分:0)

看一下这篇文章:Shortest possible encoded string with decode possibility (shorten url) using only PHP

他能够将 39个字符 字符串编码为 30个字符 字符串并对其进行解码再次。

以下是编码功能:

function compress($input, $ascii_offset = 38){
    $input = strtoupper($input);
    $output = '';
    //We can try for a 4:3 (8:6) compression (roughly), 24 bits for 4 chars
    foreach(str_split($input, 4) as $chunk) {
        $chunk = str_pad($chunk, 4, '=');
        $int_24 = 0;
        for($i=0; $i<4; $i++){
            //Shift the output to the left 6 bits
            $int_24 <<= 6;
            //Add the next 6 bits
            //Discard the leading ascii chars, i.e make
            $int_24 |= (ord($chunk[$i]) - $ascii_offset) & 0b111111;
        }
        //Here we take the 4 sets of 6 apart in 3 sets of 8
        for($i=0; $i<3; $i++) {
            $output = pack('C', $int_24) . $output;
            $int_24 >>= 8;
        }
    }
    return $output;
}

解码功能:

function decompress($input, $ascii_offset = 38) {
    $output = '';
    foreach(str_split($input, 3) as $chunk) {
        //Reassemble the 24 bit ints from 3 bytes
        $int_24 = 0;
        foreach(unpack('C*', $chunk) as $char) {
            $int_24 <<= 8;
            $int_24 |= $char & 0b11111111;
        }
        //Expand the 24 bits to 4 sets of 6, and take their character values
        for($i = 0; $i < 4; $i++) {
            $output = chr($ascii_offset + ($int_24 & 0b111111)) . $output;
            $int_24 >>= 6;
        }
    }
    //Make lowercase again and trim off the padding.
    return strtolower(rtrim($output, '='));
}

他还建议通过加密和解密数据,在此过程中保护此信息的安全。

以下是调用上述函数的完整代码:

$method = 'AES-256-CBC';
$secret = base64_decode('tvFD4Vl6Pu2CmqdKYOhIkEQ8ZO4XA4D8CLowBpLSCvA=');
$iv = base64_decode('AVoIW0Zs2YY2zFm5fazLfg==');
$input = 'img=/dir/dir/hi-res-img.jpg&w=700&h=500';
var_dump($input);
$compressed = compress($input);
var_dump($compressed);
$encrypted = openssl_encrypt($compressed, $method, $secret, false, $iv);
var_dump($encrypted);
$decrypted = openssl_decrypt($encrypted, $method, $secret, false, $iv);
var_dump($decrypted);
$decompressed = decompress($compressed);
var_dump($decompressed);

你可以尝试一下。

相关问题