零宽字符是一种特殊的字符,它可以被插入到文本中而不影响文本的可见性。在URL中,零宽字符可以被用来隐藏URL中的信息,或者在URL中插入额外的数据。

<?php

/**
 * Created by PhpStorm.
 * User: LinFei
 * Created time 2023/01/18 18:00:37
 * E-mail: fly@eyabc.cn
 */
declare (strict_types=1);

class SpaceCrypt
{
    /**
     * Encoding to zero-width characters
     * @param string $content
     * @return string
     */
    public static function encrypt(string $content): string
    {
        return self::binToHidden(self::strToBin($content));
    }

    /**
     * Decode zero-width characters
     * @param string $content
     * @return string
     */
    public static function decrypt(string $content): string
    {
        return self::binToStr(self::hiddenToBin($content));
    }

    /**
     * String to binary
     * @param string $text
     * @return string
     */
    protected static function strToBin(string $text): string
    {
        $bin = [];
        for ($i = 0; strlen($text) > $i; $i++)
            $bin[] = decbin(ord($text[$i]));
        return implode(' ', $bin);
    }

    /**
     * Convert binary data to a string
     * @param string $bin
     * @return string
     */
    protected static function binToStr(string $bin): string
    {
        $text = [];
        $bin = explode(' ', $bin);
        for ($i = 0; count($bin) > $i; $i++)
            $text[] = chr(bindec($bin[$i]));
        return implode($text);
    }

    /**
     * Convert the ones, zeros, and spaces of the hidden binary data to their respective zero-width characters
     * @param string $str
     * @return string
     */
    protected static function binToHidden(string $str): string
    {
        // Unicode Character 'WORD JOINER' (U+2060) 0xE2 0x81 0xA0
        $str = str_replace(' ', "\xE2\x81\xA0", $str);
        // Unicode Character 'ZERO WIDTH SPACE' (U+200B) 0xE2 0x80 0x8B
        $str = str_replace('0', "\xE2\x80\x8B", $str);
        // Unicode Character 'ZERO WIDTH NON-JOINER' (U+200C) 0xE2 0x80 0x8C
        return (string)str_replace('1', "\xE2\x80\x8C", $str);
    }

    /**
     * Convert zero-width characters to hidden binary data
     * @param string $str
     * @return string
     */
    protected static function hiddenToBin(string $str): string
    {
        // Unicode Character 'WORD JOINER' (U+2060) 0xE2 0x81 0xA0
        $str = str_replace("\xE2\x81\xA0", ' ', $str);
        // Unicode Character 'ZERO WIDTH SPACE' (U+200B) 0xE2 0x80 0x8B
        $str = str_replace("\xE2\x80\x8B", '0', $str);
        // Unicode Character 'ZERO WIDTH NON-JOINER' (U+200C) 0xE2 0x80
        return (string)str_replace("\xE2\x80\x8C", '1', $str);
    }
}

$wd = SpaceCrypt::encrypt('123');
var_dump('url: https://www.eyabc.cn/?wd=' . $wd);
var_dump('key: ' . SpaceCrypt::decrypt($wd));