简体   繁体   English

PHP base64编码自定义字母表

[英]PHP base64 encoding custom alphabet

I try to use base64_encode() and base64_decode() but with custom alphabet. 我尝试使用base64_encode()和base64_decode(),但使用自定义字母表。 Default alphabet is: 默认字母表是:

"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

say I want to use: 说我想用:

"ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba9876543210+/" 

found a class on internet but doesn't work as expected. 在互联网上找到了一个班级,但没有按预期工作。 Any idea on how to achieve this as simple as possible? 关于如何尽可能简单地实现这一点的任何想法?

Ultra easy, strtr can do this out of the box: 超级简单, strtr可以开箱即用:

$default = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
$custom  = "ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba9876543210+/";

$encoded = strtr(base64_encode($input), $default, $custom);

In addition to the custom encoding defined above, to decode with a custom alphabet, you can do the following: 除了上面定义的自定义编码,要使用自定义字母解码,您还可以执行以下操作:

    $custom = 'ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba9876543210+/';
    $default = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
    $decoded = base64_decode(strtr($input, $custom, $default));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM