$search = str_split(" :\"");
$replace ="_";
$filename = str_replace($search, $replace, $filename);
$fname = str_replace(array('\\','/',':','*','?','"','<','>','|'),' ',$filename);
This helper class available here [https://noiselabs.io/2011/04/25/sanitize-filenames-with-php/]<?php
class Helper
{
/**
* Returns a safe filename, for a given platform (OS), by
* replacing all dangerous characters with an underscore.
*
* @param string $dangerousFilename The source filename
* to be "sanitized"
* @param string $platform The target OS
*
* @return string A safe version of the input
* filename
*/
public static function sanitizeFileName($dangerousFilename, $platform = 'Unix')
{
if (in_array(strtolower($platform), array('unix', 'linux'))) {
// our list of "dangerous characters", add/remove
// characters if necessary
$dangerousCharacters = array(" ", '"', "'", "&", "/", "\\", "?", "#");
} else {
// no OS matched? return the original filename then...
return $dangerousFilename;
}
// every forbidden character is replace by an underscore
return str_replace($dangerousCharacters, '_', $dangerousFilename);
}
}
Usage:$safeFilename = Helper::sanitizeFileName('#my unsaf&/file\name?"');
// 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);
Source https://stackoverflow.com/questions/2021624/string-sanitizer-for-filename#answer-2021729
Open in new window