string sanitizer for filename

后端 未结 17 1369
长情又很酷
长情又很酷 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 13:54

    Making a small adjustment to Tor Valamo's solution to fix the problem noticed by Dominic Rodger, you could use:

    // Remove anything which isn't a word, whitespace, number
    // or any of the following caracters -_~,;[]().
    // If you don't need to handle multi-byte characters
    // you can use preg_replace rather than mb_ereg_replace
    // Thanks @Łukasz Rysiak!
    $file = mb_ereg_replace("([^\w\s\d\-_~,;\[\]\(\).])", '', $file);
    // Remove any runs of periods (thanks falstro!)
    $file = mb_ereg_replace("([\.]{2,})", '', $file);
    

提交回复
热议问题