Replacing Non Alphanumeric Character in PHP

Wednesday, December 17, 2008

I use this when I want to change the filename uploaded by trusted user to server, it simply change non alphanumeric character (including space) into underscore.

<?php
$fileName = preg_replace ( '/[^a-zA-Z0-9]/u', '_', $fileNameStripped ); 
//code to upload the file
//...
?>
In my case, I strip the file from the extension 'cause I dont want the preg_replace to change the dot extension (ex: .jpg) into _jpg. It goes like
$fileNameStripped = 
substr($_FILES['thmbFile']['name'], 0,  strripos($_FILES['thmbFile']['name'], '.') )


Hope it helps.

0 comments: