Alex Rivera | Logout

string sanitizer for filename

Asked 2010-01-07T15:58:25.650
165

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 worried that I'll overlook a character! )

Edit: for saving files on a Windows NTFS filesystem.

Edit
Report

3 Answers

7

Making a small adjustment to Sean Vieira's solution to allow for single dots, you could use:

preg_replace("([^\w\s\d\.\-_~,;:\[\]\(\)]|[\.]{2,})", '', $file)
answered 2013-07-12T23:59:36.450
6

The following expression creates a nice, clean, and usable string:

/[^a-z0-9\._-]+/gi

Turning today's financial: billing into today-s-financial-billing

answered 2010-01-07T16:01:15.690
0

one way

$bad='/[\/:*?"<>|]/';
$string = 'fi?le*';

function sanitize($str,$pat)
{
    return preg_replace($pat,"",$str);

}
echo sanitize($string,$bad);
answered 2010-01-08T00:56:09.117

Your Answer