dongwu8050 2016-10-06 20:21
浏览 100
已采纳

在PHP中转换字符串以用作文件名...而不剥离特殊字符

Our current system saves files that match the name of their parent group. So a group named "My Devices" saves an image called "My+Devices.jpg". This worked great, and even though there was some trouble with the name getting converted somewhere along the line of PHP and JS to "My%20Devices.jpg", I was able to just convert spaces to plus signs before that happened.

Now we need to account for other special characters, like apostrophes so that a group can be named "Joe's Devices". I need some way to convert that to something that can be a file name. BUT I can't just strip out the special characters or there could be a collision if someone uses a group name of "Joes Devices" (without the apostrophe).

I tried urlencode() and rawurlencode(), but those use percent signs, which are great for URLs but not so much for file names. I thought base64_encode() would be better even though it's a much longer string. But it includes equal signs which are no good for filenames.

Is there a way to convert a string to a filename-friendly string, one that can be decoded back to it's original string? Or do I need to recode this feature completely and use an ID match or something?

  • 写回答

2条回答 默认 最新

  • doulu1325 2016-10-06 20:43
    关注

    Your quest is very similar to questions around creating url-safe base64 encoded strings.

    See this answer for one example: https://stackoverflow.com/a/5835352/660694

    My solution would be a variation of this.

    In one of my apps I have this wrapper function:

    function base64_safe_encode($input, $stripPadding = false)
    {
        $encoded = strtr(base64_encode($input), '+/=', '-_~');
    
        return ($stripPadding) ? str_replace("~","",$encoded) : $encoded;
    }
    

    Now you can generate a filename or url safe base64 encoded string that is easily reversible.

    Note there is an option to strip the padding at the end of the string if you like, PHP does not require the padding characters to be present when you decode.

    The decode function is then quite simple:

    function base64_safe_decode($input)
    {
        return base64_decode(strtr($input, '-_~', '+/='));
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭