从 PHP 字符串中删除不是 a-zA-Z0-9、_ 和 - 的字符
我想阻止所有与此正则表达式模式不匹配的字符:[a-zA-Z0-9_-]
。
通常我会这样做:
preg_replace("[a-zA-Z0-9_-]", "", $var);
但显然这与我想要的效果相反。正则表达式中有 NOT 吗?我怎样才能去掉任何与模式不匹配的字符?
谢谢。
I want to stop out all characters that do NOT match this regex pattern: [a-zA-Z0-9_-]
.
Usually I would do this:
preg_replace("[a-zA-Z0-9_-]", "", $var);
but obviously this has the oposite effect to what I want. Is there a NOT in regex? How can I get this to strip out any characters that do not match the pattern?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这:
甚至不会替换这些字符,除非输入字符串正是模式。通过使用
[]
作为分隔符,它们的效果与表达式本身的效果不同。您可以更改分隔符(例如:/
),或在模式中添加更多括号:现在,在
[]
中否定模式 ,您可以在开头使用^
:您还可以使用不敏感修饰符
i
来匹配小写 (az
) 和大写 (>AZ
):This:
wouldn't even replace those characters, except if the input string is exactly the pattern. By using
[]
as delimiters, they have not the same effect as their would in the expression itself. You could change your delimiter (e.g.:/
), or add some more brackets in the pattern:Now, to negate a pattern in
[]
, you use^
at the beginning:You could also have used the insensitive modifier
i
to match both lowercase (a-z
) and uppercase (A-Z
):[^a-zA-Z0-9_-]
应该为你做。请注意括号内的^
。[^a-zA-Z0-9_-]
should do it for you. Note the^
inside the bracket.在正则表达式的范围元素中,如果第一个字符是
^
,则会反转范围(因此[^a-zA-Z0-9_-]
匹配任何字符这不是字母数字、下划线或破折号)大多数类型的正则表达式都是如此
In a range element of the regular expression, if the first character is
^
, it inverts the range (hence[^a-zA-Z0-9_-]
matches any character that's not alphanumeric, underscore or dash)This is true with most types of regular expressions
字符前面的 ^ 字符怎么样:
How about a ^ character in front the characters: