How to convert a filename with special chars to be acceptable by all OS in PHP?

How to convert a filename with special chars to be acceptable by all OS in PHP?

To convert a filename with special characters to be acceptable by all operating systems in PHP, you can use the preg_replace() function. This function allows you to search for a pattern in a string and replace it with a specified replacement string. You can use it to remove special characters from a filename and replace them with underscores or dashes.

Here is an example of how you could use the preg_replace() function to convert a filename with special characters to be acceptable by all operating systems:

// Set the original filename
$filename = "my file (1).txt";

// Remove special characters and replace them with underscores
$new_filename = preg_replace("/[^a-zA-Z0-9\s]/", "_", $filename);

// Output the new filename
echo $new_filename; // "my_file_1.txt"
Source‮‬:www.lautturi.com

Alternatively, you can use the str_replace() function to achieve the same result. This function allows you to search for a specified string and replace it with a specified replacement string. You can use it to remove special characters from a filename and replace them with underscores or dashes.

Here is an example of how you could use the str_replace() function to convert a filename with special characters to be acceptable by all operating systems:

// Set the original filename
$filename = "my file (1).txt";

// Define an array of special characters to remove
$special_chars = array("(", ")", ",", ".", "!", "?");

// Remove special characters and replace them with underscores
$new_filename = str_replace($special_chars, "_", $filename);

// Output the new filename
echo $new_filename; // "my_file_1.txt"

In both cases, the resulting filename will be compatible with all operating systems and can be easily accessed and used.

Created Time:2017-10-18 14:57:43  Author:lautturi