简体   繁体   中英

Replace all spaces with dashes, but not accents characters - PHP

I want to replace spaces with dashes, however the code is also replacing the accents characters with dashes:

$username = preg_replace("![^a-Z0-9]+!i", "-", $username);

How do I leave the letters with accents not replaced by dashes?

If you are only changing spaces, in your RegEx, try matching the spaces.

$username = preg_replace("![ ]+!i", "-", $username);

I would also recommend against unescaped \\ characters - they have a habit of meaning something in both PHP strings (more so with double quotes) and in RegEx.

Alternatively, \\w will match any word character, and \\d will match any number, so ![^\\w\\d]+!iu will match anything that isn't alphanumeric.

$username = preg_replace('![^\\w\\d]+!iu', '-', $username);

Note, the i makes it case-insensitive, the u makes it unicode safe.

Example:

echo preg_replace('![^\\w\\d\\\\]+!iu', '-', 'this is a testé');

outputs this-is-a-testé

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM