68 Votes

PHP: Remove invalid characters from file names

Tip by Axuter | Last update on 2021-07-01 | Created on 2013-01-23

Characters such as "?", "\", "/", "*" or "|" are not allowed in file names on Windows and other operating systems. With this line of code, you can simply delete those characters from a string with the help of PHP:

$f = 'fi?le.txt';

$f = str_replace(array('\\','/',':','*','?','"','<','>','|'),' ',$f);

echo $f; // 'fi le.txt'

The respective characters are simply replaced by a space.

Alternatively, you can also just use another character instead of the space or write '' to the replace function in order to delete the characters completely.


About the Author

AvatarThe author has not added a profile short description yet.
Show Profile


Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.


Ask your own question or write your own article on askingbox.com. That’s how it’s done.