从 PHP 字符串中删除不是 a-zA-Z0-9、_ 和 - 的字符

发布于 2024-10-18 00:25:22 字数 208 浏览 3 评论 0原文

我想阻止所有与此正则表达式模式不匹配的字符:[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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

哭了丶谁疼 2024-10-25 00:25:22

这:

preg_replace("[a-zA-Z0-9_-]", "", $var);

甚至不会替换这些字符,除非输入字符串正是模式。通过使用 [] 作为分隔符,它们的效果与表达式本身的效果不同。您可以更改分隔符(例如:/),或在模式中添加更多括号:

preg_replace("/[a-zA-Z0-9_-]/", "", $var);    // this works
preg_replace("[[a-zA-Z0-9_-]]", "", $var);    // this too

现在,在[]否定模式 ,您可以在开头使用 ^

preg_replace("/[^a-zA-Z0-9_-]/", "", $var);

您还可以使用不敏感修饰符 i 来匹配小写 (az) 和大写 (>AZ):

preg_replace("/[^a-z0-9_-]/i", "", $var);   // same as above

This:

preg_replace("[a-zA-Z0-9_-]", "", $var);

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:

preg_replace("/[a-zA-Z0-9_-]/", "", $var);    // this works
preg_replace("[[a-zA-Z0-9_-]]", "", $var);    // this too

Now, to negate a pattern in [], you use ^ at the beginning:

preg_replace("/[^a-zA-Z0-9_-]/", "", $var);

You could also have used the insensitive modifier i to match both lowercase (a-z) and uppercase (A-Z):

preg_replace("/[^a-z0-9_-]/i", "", $var);   // same as above
做个ˇ局外人 2024-10-25 00:25:22

[^a-zA-Z0-9_-] 应该为你做。请注意括号内的 ^

[^a-zA-Z0-9_-] should do it for you. Note the ^ inside the bracket.

冷血 2024-10-25 00:25:22

在正则表达式的范围元素中,如果第一个字符是 ^,则会反转范围(因此 [^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

月棠 2024-10-25 00:25:22

字符前面的 ^ 字符怎么样:

preg_replace( '[^a-zA-Z0-9_-]", "", $var);

How about a ^ character in front the characters:

preg_replace( '[^a-zA-Z0-9_-]", "", $var);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文