Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove whitespace and special character from string

Tags:

php

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;
    }
}
like image 419
raju Avatar asked Jun 10 '12 18:06

raju


People also ask

How do I remove special characters and spaces from a string?

Use the replace() method to remove all special characters from a string, e.g. str. replace(/[^a-zA-Z0-9 ]/g, ''); .

What removes whitespace from the string?

stripleading() method removes the spaces present at the beginning of the string. striptrailing() method removes the spaces present at the end of the string. replaceall(String regex, String replacement) method replaces all the matched substring with a new string.

Is whitespace a special character?

Special characters are those characters that are neither a letter nor a number. Whitespace is also not considered a special character.

How do I remove special characters from a string in Python?

But by using the ord() function, this function returns the Unicode of a character. This can be used to remove a character from a string.


1 Answers

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

$input = preg_replace("/[^a-zA-Z]+/", "", $input);
like image 176
John Avatar answered Oct 28 '22 11:10

John