选择性字符串减少
我想知道如何从字符串中去除除下划线和破折号之外的所有非字母数字字符。
I would like to know how to strip all non-alphanumeric characters from a string except for underscores and dashes in PHP.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将
preg_replace
与/[^a-zA-Z0-9_\- ]/
作为模式,''
作为替换。编辑
正如skipy所说,您可以使用
i
修饰符来不区分大小写:Use
preg_replace
with/[^a-zA-Z0-9_\-]/
as the pattern and''
as the replacement.EDIT
As skippy said, you can use the
i
modifier for case insensitivity:使用
preg_replace
:preg_replace
的第一个参数是常规的表达。其中包含:/
- 起始分隔符 - 开始正则表达式[
- 起始字符类 - 定义可以匹配的字符^
- 负数-- 使字符类仅匹配与\w
后面的选择不匹配的字符A-Za-z0-9
和_
(下划线)-
- 连字符 - 也不匹配连字符]
- 关闭字符类/
- 结束定界符 - 关闭正则表达式请注意,这仅匹配连字符(即 -)。它与真正的破折号字符(– 或 —)不匹配。
Use
preg_replace
:The first argument to
preg_replace
is a regular expression. This one contains:/
- starting delimiter -- start the regex[
- start character class -- define characters that can be matched^
- negative -- make the character class match only characters that don't match the selection that follows\w
- word character -- so don't match word characters. These areA-Za-z0-9
and_
(underscore)-
- hyphen -- don't match hypens either]
- close the character class/
- ending delimiter -- close the regexNote that this only matches hyphens (i.e. -). It does not match genuine dash characters (– or —).
接受 az、AZ、0-9、'-'、'_' 和空格:
无空格:
Accepts a-z, A-Z, 0-9, '-', '_' and spaces:
No spaces: