How to generate filenames from a given string by replacing spaces and special characters using PHP preg_replace()

| | 1 min read

You might have come across a situation where you need to set the title of the content as the filename for an uploaded image or where you might need to replace the spaces and special characters from the filename of an uploaded file. In such conditions you can use preg_replace. I will show you some example code where the output string will be nice and clean and can be used for setting file names.

Example Case:

Given below is a test string. I have added several special characters and along with numbers and alphabets. The output that I want is something with only lowercase letters, numbers and underscores.

Code:

// String to be converted.
$string = " Inside 'the'....---- Quotes !@$%^&*() IS THE STRING?/. [Lets] {filter} this & & string! AND 123 GO";

// Conversion method.
$cleanstring = strtolower(trim(preg_replace('#\W+#', '_', $string), '_'));

// Displaying output.
echo $cleanstring;

Output:

inside_the_quotes_is_the_string_lets_filter_this_string_and_123_go