Javascript& php:如何编码编码短字符串中的普通字符串?

时间:2016-03-28 15:29:52

标签: javascript php decode encode

我有一个普通的字符串:

var string = "Hello i'm fine"

我想用短编码字符串对其进行编码。

我想通过解码短字符串来检索原始的长字符串。

Base64不适合我,因为base64输出长度大于原始字符串长度。

所以我想在javascript和php中找到一种方法。

一个想法?

1 个答案:

答案 0 :(得分:1)

对于你的例子来说,短信不是那么容易(见下文)。但是如果输入的字符串较长,则可以将compress函数与base64编码结合使用:

<?php
$input = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt.";

$encoded = base64_encode(gzdeflate($input));
$decoded = gzinflate(base64_decode($encoded));
var_dump($encoded);
var_dump($decoded);

输入有489个字符,编码只有372!

string(372) "PVHZTcQwEG1lCojSA4IfJEQPxh7CIF87x9bPc7LLhyUf7xx/DOVGMi0alVGHkolTauwb5dGNs7MHK6UiUyxLP4ir+E4v3Dl1gFobZVCVI2oiPtgvoX9ES2Zpp1c42MgiRj35uAXTZOzkK4xAaunoeCtYM6mHCnfcju5sGyiWEURJpUiOCk4L2+ltdM50i9ToG7mAjOoqWRg2nDd41MpLYxly4ELZBVlusdDGbafPqIh+1oWSX4lPAHGX9nSZXJh+w3xs9K2YhCzanetGqQr0/bK8R53hyfmcBh41x07v/RR7CujP6BktAgBpk7UI+AlsTG2Nxegunni7CI+Q+CTJHo+y6HOFaqOu46Pa8nJYK7n0LCU6vusP"
string(489) "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt."

对于较短的字符串,可以通过巧妙地选择字符集来实现。短输入字符集和大输出字符集可以减少字符串的长度。 阅读:Shortest possible encoded string with decode possibility (shorten url) using only PHP

在Javascript中,概念是相同的,但也许您需要一个用于压缩的库。

请记住:这不是仅加密编码!不要用它来隐藏信息