Is there any way to get the file extension from a URL

前端 未结 7 1310
囚心锁ツ
囚心锁ツ 2021-02-12 06:48

I want to know that for make sure that the file that will be download from my script will have the extension I want.

The file will not be at URLs like:

h         


        
7条回答
  •  伪装坚强ぢ
    2021-02-12 07:45

    I know that this is an old question, but can be helpful to people that see this question.

    The best approach for getting an extension from filename inside an URL, also with parameters are with regex.

    You can use this pattern (not urls only):

    .+(\.\w{3})\?*.*
    

    Explanation:

    .+     Match any character between one and infinite
    (...)  With this, you create a group, after you can use for getting string inside the brackets
    \.     Match the character '.'
    \w     Matches any word character equal to [a-zA-Z0-9_]
    \?*    Match the character '?' between zero and infinite
    .*     Match any character between zero and infinite
    

    Example:

    http://example.com/file.png
    http://example.com/file.png?foo=10
    
    But if you have an URL like this:
    
    http://example.com/asd
    This take '.com' as extension.
    

    So you can use a strong pattern for urls like this:

    .+\/{2}.+\/{1}.+(\.\w+)\?*.*
    

    Explanation:

    .+        Match any character between one and infinite
    \/{2}     Match two '/' characters
    .+        Match any character between one and infinite
    \/{1}     Match one '/' character
    .+        Match any character between one and infinite
    (\.\w+)  Group and match '.' character and any word character equal to [a-zA-Z0-9_] from one to infinite
    \?*       Match the character '?' between zero and infinite
    .*        Match any character between zero and infinite
    

    Example:

    http://example.com/file.png          (Match .png)
    https://example.com/file.png?foo=10  (Match .png)
    http://example.com/asd               (No match)
    C:\Foo\file.png                      (No match, only urls!)
    
    http://example.com/file.png
    
        http:        .+
        //           \/{2}
        example.com  .+
        /            \/{1}
        file         .+
        .png         (\.\w+)
    

提交回复
热议问题