替换 PHP 字符串中选定的字符
我知道这个问题肯定已经被问过好几次了,但是我在正则表达式方面遇到了问题...所以这是我想在 PHP 中做的(简单)事情:
我想创建一个函数来替换字符串中不需要的字符。接受的字符应该是: az AZ 0-9 _ - + ( ) { } # äöü äÖÜ 空格
我希望所有其他字符都更改为“_”。这是一些示例代码,但我不知道要填写什么 ??????:
<?php
// sample strings
$string1 = 'abd92 s_öse';
$string2 = 'ab! sd$ls_o';
// Replace unwanted chars in string by _
$string1 = preg_replace(?????, '_', $string1);
$string2 = preg_replace(?????, '_', $string2);
?>
输出应该是: $string1: abd92 s_öse (相同) $string2: ab_ sd_ls_o
我能够使其适用于 az, 0-9,但最好允许这些附加字符,尤其是 äöü。感谢您的投入!
I know this question has been asked several times for sure, but I have my problems with regular expressions... So here is the (simple) thing I want to do in PHP:
I want to make a function which replaces unwanted characters of strings. Accepted characters should be:
a-z A-Z 0-9 _ - + ( ) { } # äöü ÄÖÜ space
I want all other characters to change to a "_". Here is some sample code, but I don't know what to fill in for the ?????:
<?php
// sample strings
$string1 = 'abd92 s_öse';
$string2 = 'ab! sd$ls_o';
// Replace unwanted chars in string by _
$string1 = preg_replace(?????, '_', $string1);
$string2 = preg_replace(?????, '_', $string2);
?>
Output should be:
$string1: abd92 s_öse (the same)
$string2: ab_ sd_ls_o
I was able to make it work for a-z, 0-9 but it would be nice to allow those additional characters, especially äöü. Thanks for your input!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
仅允许您描述的确切字符:
允许所有空白,而不仅仅是(空格)字符:
允许来自不同字母表的字母 - 不仅是您提到的特定字符,还包括俄语和希腊语或其他类型的字母重音符号:
如果我是你,我会选择最后一个。它不仅更短、更容易阅读,而且限制更少,而且如果
äöüäÖÜ
都很好的话,阻止像и
这样的东西并没有什么特别的优势。To allow only the exact characters you described:
To allow all whitespace, not just the (space) character:
To allow letters from different alphabets -- not just the specific ones you mentioned, but also things like Russian and Greek, or other types of accent marks:
If I were you, I'd go with the last one. Not only is it shorter and easier to read, but it's less restrictive, and there's no particular advantage to blocking stuff like
и
ifäöüÄÖÜ
are all fine.将
[^a-zA-Z0-9_\-+(){}#äöüäÖÜ ]
替换为_
。^
之后的所有字符。这将替换除 [字符集] 编辑: 中转义
-
破折号的Replace
[^a-zA-Z0-9_\-+(){}#äöüÄÖÜ ]
with_
.This replaces any characters except the ones after
^
in the [character set]Edit: escaped the
-
dash.