preg_replace('/[^a-zA-Z0-9]+/', '_', $sentence)

Basically it looks for any sequence of non-alphanumeric characters and replaces it with a single '_'. This way, you also avoid having two consecutive _'s in your output.

If it's for URLs, you probably also want them to be lower-case only:

preg_replace('/[^a-z0-9]+/', '_', strtolower($sentence))

Answer from Wim on Stack Overflow
🌐
PHPBuilder
board.phpbuilder.com › d › 10263155-replace-all-special-characters-with-underscore
replace ALL special characters with underscore? - PHPBuilder Forums
December 16, 2003 - I'm writing a file upload script and in order to use ImageMagick successfully, the filename can't have any strange characters like "&" or spaces.. I'm t...
🌐
sebhastian
sebhastian.com › php-replace-special-characters
How to replace special characters in a string with PHP | sebhastian
November 30, 2022 - For example, suppose you want to replace the special character dash (-) with an underscore (_). Here’s how you do it: <?php $str = "learning-php-language"; $new = str_replace("-", "_", $str); print $new; // Output: learning_php_language
🌐
Webmaster World
webmasterworld.com › php › 4007.htm
Replace special chars by underscores - PHP Server Side Scripting forum at WebmasterWorld - WebmasterWorld
June 4, 2004 - My website is written in PHP, and ... news-message to be converted to become a valid url: ... All characters but a to z, A to z and 0 to 9 are replaced by an underscore....
Top answer
1 of 2
2

I would build a regex (character class, to be exact) using your whitelisted characters, and then remove any character which matches the negation of that class.

$allowed_char_array = array("a","b","c","d","e") // and others
$chars = implode("", $allowed_char_array);
$regex = "/[^" . $chars . "]/u";
$input = "imageЙ ййé.png";
echo $regex . "\n";
$output = preg_replace($regex, "_", $input);
echo $input . "\n" . $output;

imageЙ ййé.png
image_ __é.png

If the above be not clear, here is what the actual all to preg_replace would look like:

preg_replace("/[^abcdefghijklmnopqrstuv]/u, "_", $input);

That is, any non whitelisted character would be replaced with just underscore. I did not bother to list out the entire character class, because you already have that in your source code.

Note that the /u flag in the regex is critical here, because your input string is a UTF-8 string. UTF-8 characters may consist of more than one byte, and using preg_replace on them without /u may have unexpected results.

2 of 2
1

You will want to use mb_strtolower() to convert multibyte characters to lowercase safely.

My solution uses strtr() to convert your French accented letters to your preferred form.

Since all characters are lowercased from the onset, you can halve your white list of French characters.

Using pathinfo() helps you to dissect your filename.

Code: (Demo)

$word = 'imageЙ ййé.png';
$parts = pathinfo($word);
$filename = strtr(mb_strtolower($parts['filename']), ['é' =>'é', 'à' => 'à','è' => 'è']);
echo preg_replace('~[^ a-zéàè]~u', '_', $filename) , "." , $parts['extension'];

Output:

image_ __é.png
🌐
Java2Blog
java2blog.com › home › php › replace space with underscore in php
Replace Space with Underscore in PHP [2 ways] - Java2Blog
December 5, 2022 - Use the str_replace() function to replace with underscore in PHP, for example: str_replace(" " , "_", $str). str_replaces() returns new String with old character space( ) replaced by underscore(_) Use str_replace() method · Output · We used ...
🌐
Stack Overflow
stackoverflow.com › questions › 70221456 › converting-special-character-to-underscore-in-php
Converting special character to underscore in php - Stack Overflow
How can I convert that special character to an underscore? Thank-you. ... Don't. Use prepared statements. If there's a character set mismatch, then convert between them. Adding more and more layers of manual text mangling only kicks problems down the road. ... but please remember there will be endless possible characters you don't want.
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 29959755 › how-to-replace-multiple-random-characters-in-string-with-underscore-in-php › 29959873
How to replace multiple random characters in string with underscore(_) in PHP - Stack Overflow
Copy<?php $string = "gjhyYhK"; $percentage = 40; $total_length = strlen($string); $number_of_underscore = floor(($percentage / 100) * $total_length); // I have use floor value, you can use ceil() as well for ($i = 1; $i <= $number_of_underscore; $i++) { $random_position = rand(0, strlen($string) - 1); // get the random position of character to be replaced if (substr($string, $random_position, 1) !== '_') // check if its already replaced underscore (_) { $string = preg_replace("/" .
🌐
Devgex
devgex.com › en › article › 00020540
Implementing Space to Underscore Replacement in PHP: Methods and Best Practices - DevGex
November 23, 2025 - The str_replace function provides PHP developers with a simple yet powerful tool for handling character replacement needs in strings. In the specific application scenario of space-to-underscore replacement, this function demonstrates excellent performance and ease of use.
🌐
PHP
php.net › manual › en › function.str-replace.php
PHP: str_replace - Manual
Instead, use preg_replace: <?php $challenge = '-aaa----b-c-----d--e---f'; echo str_replace('--', '-', $challenge).'<br>'; echo preg_replace('/--+/', '-', $challenge).'<br>'; ?> This outputs the following: -aaa--b-c---d-e--f -aaa-b-c-d-e-f ... To remove all characters from string $b that exist in string $a: $a="ABC"; $b="teAsBtC"; echo str_replace(str_split($a),'',$b); Output: test To remove all characters from string $b that don't exist in string $a: $a="ABC"; $b="teAsBtC"; echo str_replace(str_split(str_replace(str_split($a),'',$b)),'',$b); Output: ABC
🌐
W3Schools
w3schools.com › php › func_string_str_replace.asp
PHP str_replace() Function
zip_close() zip_entry_close() ... zip_open() zip_read() PHP Timezones ... The str_replace() function replaces some characters with some other characters in a string....
🌐
Basantmallick
basantmallick.com › freelance website developer in delhi ncr india › php › how to replace all special characters except underscore and period in php?
how to replace all special characters except underscore and period in php?
February 20, 2021 - <?php $string="a quick borown fox jump over the lazy dog & ( jkl/)-ov"; echo $string = preg_replace('/[^a-zA-Z0-9_.]/', '-', strtolower($string)); ?>