dongqiao3214 2013-12-02 19:53
浏览 334
已采纳

将PHP字符串从24个字符压缩(缩短)到20个字符

I'm currently writing a PHP application that utilizes the Authorize.net api. This api requires that a customer's unique id value be less than 20 characters. I'm currently storing this unique customer id in Mongo as a MongoId object (24 characters).

Is there a way to convert a 24 character string to 20 so that it can meet the API requirements ?

  • 写回答

1条回答 默认 最新

  • duanjiao5261 2013-12-02 20:26
    关注

    From what I see on your referenced page, the 24-characters are hexadecimal. If customer-id may be alphanumerical you can use base_convert to shorten the number. Unfortunately the full number is > 32bit so you need to covert it in parts to make it work:

    // Pad with 0's to make sure you have 24 chars
    $padded = str_repeat('0', 24 - strlen($mongoId)) . $mongoId;
    $leastSignificant = base_convert(substr($padded, 14, 10), 16, 32); // will be 8 chars most
    $middleSignificant = base_convert(substr($padded, 4, 10), 16, 32); // will be 8 chars most
    $highSignificant = base_convert(substr($padded, 0, 4), 16, 32); // will be 4 chars most
    
    // Concatenate, and make sure everything is correctly padded
    $result = str_repeat('0', 4 - strlen($highSignificant)) . $highSignificant .
              str_repeat('0', 8 - strlen($middleSignificant )) . $middleSignificant .
              str_repeat('0', 8 - strlen($leastSignificant )) . $leastSignificant;
    echo strlen($result); // Will echo 20
    
    // Reverse the algoritm to retrieve the mongoId for a given customerId 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料