How can I replace white space in filename of uploaded file

Suf picture Suf · May 18, 2011 · Viewed 16k times · Source

I'm making a SWF uploader and have my HTML form done.

It works totally fine until I upload a SWF file with spaces in the name.

How can I replace whitespace with underscores?

I have tried...

str_replace(" ","_", $file);

...and...

preg_replace(" ","_", $file);

Answer

alex picture alex · May 18, 2011

How can I replace whitespace with underscores?

The \s character class will match whitespace characters. I've added the + quantifier to collapse multiple whitespace to one _. If you don't want that, remove the +.

$file = preg_replace('/\s+/', '_', $file);