Home » Php » php – remove whitespace and special character from string

php – remove whitespace and special character from string

Posted by: admin July 12, 2020 Leave a comment

Questions:

i am using this code to save the uploaded file but the problem is it is allowing the file with name with special character and space.
for example it is allowing

hi how are you

but i dont want to allow any space ,special charater etc. here is my code .i tried with preg_replace in uri but after that i tried to upload file but nothing got uploaded.

function save_file($file) {
    $allowed_ext = array('jpg','png','gif','jpeg');
    $ext = $file['name'];
    $ext = strtolower($ext);

    if (in_array($ext, $allowed_ext)) {
        die('Sorry, the file type is incorrect:'.$file['name']);
    }

    $fname = date("H_i",time()).'_'.get_rand(5);
    $dir = date("Ym",time());
    $folder = 'uploads/userfiles/'.$dir;
    $uri = $folder.'/'.$fname.'.'.$ext;

    if (!is_dir($folder))
        mkdir($folder, 0777);

    if (copy($file['tmp_name'],$uri))
        return $uri;
    else {
        return false;
    }
}
How to&Answers:

To strip non letters out of a string you can use the following regular expression

$input = preg_replace("/[^a-zA-Z]+/", "", $input);