You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP中实现自定义文本哈希算法(含字符映射规则)

Hey there! Let's walk through how to build this custom character mapping system in PHP. What you're describing is essentially a substitution cipher (direct character-to-string replacement) rather than a traditional cryptographic hash—great for non-security use cases like custom obfuscation or formatting. Here's a clean, maintainable implementation:

Step 1: Define Your Character Mapping

First, create an associative array that holds all your desired character-to-string mappings. This is the core of your algorithm, and you can expand it with as many rules as you need:

// Your custom character mapping array
$charMap = [
    'a' => 'xyz',
    'b' => '256',
    // Add more mappings here:
    'c' => '!@#',
    '1' => 'abc',
    'A' => 'XYZ', // Handle uppercase if needed
    ' ' => '-',   // Even spaces can be mapped
];
Step 2: Build the Encryption Function

Next, write a function that iterates over each character in your input string, replaces it with the mapped value (if it exists), and builds the final encrypted string:

function customEncrypt(string $input, array $charMap): string {
    $encrypted = '';
    
    // Loop through every character in the input
    for ($i = 0; $i < strlen($input); $i++) {
        $currentChar = $input[$i];
        // Use the mapped value if available; otherwise keep the original character
        $encrypted .= $charMap[$currentChar] ?? $currentChar;
    }
    
    return $encrypted;
}

Example Usage

Test it out with a sample string:

$original = "Hello aBc123!";
$encrypted = customEncrypt($original, $charMap);
echo $encrypted; 
// Output: Hello xyz256!@#abc23!
Step 3: (Optional) Add Decryption Support

If you need to reverse the process, you'll need a reverse mapping and a function that scans for mapped values in the encrypted string. Important: Make sure all your mapped values are unique—otherwise decryption will be ambiguous!

First, create the reverse map:

// Reverse the mapping array (only works if all mapped values are unique!)
$reverseMap = array_flip($charMap);

Then build the decryption function. Since mapped values can be multiple characters long, we'll check from the longest possible length down to 1 to avoid false matches:

function customDecrypt(string $input, array $reverseMap): string {
    $decrypted = '';
    $inputLength = strlen($input);
    $i = 0;
    
    // Get the length of the longest mapped value (adjust if your mappings are longer)
    $maxMapLength = max(array_map('strlen', array_keys($reverseMap)));
    
    while ($i < $inputLength) {
        $foundMatch = false;
        
        // Check for matches starting with the longest possible substring
        for ($length = $maxMapLength; $length >= 1; $length--) {
            if ($i + $length > $inputLength) continue;
            
            $substring = substr($input, $i, $length);
            if (isset($reverseMap[$substring])) {
                $decrypted .= $reverseMap[$substring];
                $i += $length;
                $foundMatch = true;
                break;
            }
        }
        
        // If no match found, keep the original character and move on
        if (!$foundMatch) {
            $decrypted .= $input[$i];
            $i++;
        }
    }
    
    return $decrypted;
}

Example Decryption

$decrypted = customDecrypt($encrypted, $reverseMap);
echo $decrypted; 
// Output: Hello aBc123!
Important Notes
  • Security Warning: This is not a secure encryption method for sensitive data (like passwords). For security-critical use cases, use PHP's built-in password_hash() and password_verify() functions instead.
  • Unique Mappings: For decryption to work reliably, every mapped value must be unique. If two different characters map to the same string, decryption won't know which original character to use.
  • Flexibility: You can easily expand the $charMap array with more rules as needed—just add new key-value pairs.

内容的提问来源于stack exchange,提问作者Vlad S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:50:22