Make PHP pathinfo() return the correct filename if the filename is UTF-8

后端 未结 7 875
庸人自扰
庸人自扰 2020-12-06 04:07

When using PHP\'s pathinfo() function on a filename known to be UTF-8, it does not return the correct value, unless there are \'normal\' characters in front of

7条回答
  •  南笙
    南笙 (楼主)
    2020-12-06 04:28

    A temporary work-around for this problem appears to be to make sure there is a 'normal' character in front of the accented characters, like so:

    function getFilename($path)
    {
        // if there's no '/', we're probably dealing with just a filename
        // so just put an 'a' in front of it
        if (strpos($path, '/') === false)
        {
            $path_parts = pathinfo('a'.$path);
        }
        else
        {
            $path= str_replace('/', '/a', $path);
            $path_parts = pathinfo($path);
        }
        return substr($path_parts["filename"],1);
    }
    

    Note that we replace all occurrences of '/' with '/a' but this is okay, since we return starting at offset 1 of the result. Interestingly enough, the dirname part of pathinfo() does seem to work, so no workaround is needed there.

提交回复
热议问题