简体   繁体   English

用破折号替换所有空格,但不要重音字符-PHP

[英]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. 如果仅更改空格,请在RegEx中尝试匹配空格。

$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. 我还建议不要使用不转义的\\字符-它们习惯在PHP字符串(使用双引号)和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. 另外, \\w将匹配任何单词字符, \\d将匹配任何数字,因此![^\\w\\d]+!iu将匹配任何非字母数字的字符。

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

Note, the i makes it case-insensitive, the u makes it unicode safe. 注意, i使它不区分大小写, u使它成为Unicode安全。

Example: 例:

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

outputs this-is-a-testé 输出this-is-a-testé

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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