79 Votes

PHP: Remove invalid characters from file names

Tip by Axuter | Last update on 2024-01-16 | Created on 2013-01-23

Characters such as "?", "\", "/", "*" or "|" are not allowed in file names on Windows and other operating systems. Therefore, we need to remove these characters from a string if we want to use it as a file name.

With this line of code, you can simply delete those characters from an arbitrary 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 here.

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 without any substitute.

ReplyPositiveNegative

About the Author

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

 

Related Topics

Rename File to its Folder Name

Tutorial | 0 Comments

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.

Participate

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