Hide your secret files INSIDE photos, videos or other files with OmniHide PRO.

Remove invalid characters from a filename


function filename_safe($filename) {
$temp $filename;

// Lower case
$temp strtolower($temp);

// Replace spaces with a '_'
$temp str_replace(" ""_"$temp);

// Loop through string
$result '';
for (
$i=0$i<strlen($temp); $i++) {
if (
preg_match('([0-9]|[a-z]|_)'$temp[$i])) {
$result $result $temp[$i];

// Return filename
return $result;

Discover upcoming movies

12 responses to “Remove invalid characters from a filename”

  1. looking forward for more articles on your blog Cool to read, worth learning! Keep it up! http://www.canadagoose-paris.com/doudoune-canada-

  2. I noticed the code is incorrect:
    Should be : $filename = preg_replace("/[^a-z0-9_-s.]/i","",$filename);

    Also noticed that this works:
    $filename = preg_replace("/[^.a-z0-9_-]/i","",$filename); // not sure about this technique, please comment if breaks. top one seems best

  3. Julien says:


    would do the same (and faster: one line and preg is faster than str_replace)

    For files though you might want to allow more characters, such as:


    In English: replace anything that's NOT a to z, 0 to 9, a ".", a "-" or a "_", case insensitive, with nothing.

  4. Claudio says:

    I am trying to modify the search pattern to include only numbers, decimal separator (.) and aritmethic operators (+,-,*,/) with no success.

    Anybody can help me?

    Greetings from Paraguay.

    Claudio Bogado Pompa.

  5. Terenn says:

    preg_match('#[0-9a-z_]#', $temp[$i])

    would do the trick too

  6. riesurya says:

    That what I looking for since this morning. Thanks a lot 🙂

  7. hitendra says:

    hi friends, visit this new arena to code and other things. http://hktech.info

  8. Jawsper says:

    uhm… try this:



  9. parveen sharma says:

    How do you remove characters such as “�” from this string, as well as the html code?

  10. Richard says:

    Just what I needed, cheers!

  11. aaaaa says:



We’re on Hostgator and we love it

Use coupon BLOGULATE994 and get 9.94$ flat off from any hosting package of your choice!

We're on Hostgator and are extremely happy with the service. Never down, cheap and powerful servers!
Use coupon BLOGULATE994 and get 9.94$ flat off from any hosting package of your choice!

Search Blogulate