Remove invalid characters from a filename
<?php
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;
}
?>
thanks
Just what I needed, cheers!
How do you remove characters such as “�” from this string, as well as the html code?
uhm… try this:
<code>
</code>
hi friends, visit this new arena to code and other things. http://hktech.info
That what I looking for since this morning. Thanks a lot 🙂
preg_match('#[0-9a-z_]#', $temp[$i])
would do the trick too
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.
$fileName=preg_replace("/[^a-z0-9_]/i","",$fileName);
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:
$fileName=preg_replace("/[^a-z0-9_-.]/i","",$fileName);
In English: replace anything that's NOT a to z, 0 to 9, a ".", a "-" or a "_", case insensitive, with nothing.
Please test your code thoroughly!! This should actually be:
$filename = preg_replace("/[^a-z0-9_-s.]/i","",$filename);
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
looking forward for more articles on your blog Cool to read, worth learning! Keep it up! http://www.canadagoose-paris.com/doudoune-canada-…