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 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?