string sanitizer for filename

后端 未结 17 1302
长情又很酷
长情又很酷 2020-11-27 13:23

I\'m looking for a php function that will sanitize a string and make it ready to use for a filename. Anyone know of a handy one?

( I could write one, but I\'m worri

17条回答
  •  独厮守ぢ
    2020-11-27 14:16

    SOLUTION 1 - simple and effective

    $file_name = preg_replace( '/[^a-z0-9]+/', '-', strtolower( $url ) );

    • strtolower() guarantees the filename is lowercase (since case does not matter inside the URL, but in the NTFS filename)
    • [^a-z0-9]+ will ensure, the filename only keeps letters and numbers
    • Substitute invalid characters with '-' keeps the filename readable

    Example:

    URL:  http://stackoverflow.com/questions/2021624/string-sanitizer-for-filename
    File: http-stackoverflow-com-questions-2021624-string-sanitizer-for-filename
    

    SOLUTION 2 - for very long URLs

    You want to cache the URL contents and just need to have unique filenames. I would use this function:

    $file_name = md5( strtolower( $url ) )

    this will create a filename with fixed length. The MD5 hash is in most cases unique enough for this kind of usage.

    Example:

    URL:  https://www.amazon.com/Interstellar-Matthew-McConaughey/dp/B00TU9UFTS/ref=s9_nwrsa_gw_g318_i10_r?_encoding=UTF8&fpl=fresh&pf_rd_m=ATVPDKIKX0DER&pf_rd_s=desktop-1&pf_rd_r=BS5M1H560SMAR2JDKYX3&pf_rd_r=BS5M1H560SMAR2JDKYX3&pf_rd_t=36701&pf_rd_p=6822bacc-d4f0-466d-83a8-2c5e1d703f8e&pf_rd_p=6822bacc-d4f0-466d-83a8-2c5e1d703f8e&pf_rd_i=desktop
    File: 51301f3edb513f6543779c3a5433b01c
    

提交回复
热议问题