从 PHP 中的字符串中去除除字母数字字符以外的所有内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/840948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:02:36  来源:igfitidea点击:

Stripping everything but alphanumeric chars from a string in PHP

phpregexstring

提问by Click Upvote

I'd like a regexp or other string which can replace everything except alphanumeric chars (a-zand 0-9) from a string. All things such as ,@#$(@*810should be stripped. Any ideas?

我想要一个正则表达式或其他字符串,它可以替换字符串中除字母数字字符(a-z0-9)之外的所有内容。所有的东西,@#$(@*810都应该被剥离。有任何想法吗?

Edit: I now need this to strip everything but allow dots, so everything but a-z, 1-9, .. Ideas?

编辑:我现在需要它来去除所有东西但允许点,所以除了a-z, 1-9, .. 想法?

回答by gnarf

$string = preg_replace("/[^a-z0-9.]+/i", "", $string);

Matches one or more characters not a-z 0-9 [case-insensitive], or "." and replaces with ""

匹配一个或多个非 az 0-9 [不区分大小写] 或“.”的字符。并替换为“”

回答by Corban Brook

I like using [^[:alnum:]] for this, less room for error.

我喜欢使用 [^[:alnum:]] 来减少出错的空间。

preg_replace('/[^[:alnum:]]/', '', "(ABC)-[123]"); // returns 'ABC123'

回答by SilentGhost

/[^a-z0-9.]/

should do the trick

应该做的伎俩

回答by Ilya Birman

Try:

尝试:

$string = preg_replace ('/[^a-z0-9]/i', '', $string);

/i stands for case insensitivity (if you need it, of course).

/i 代表不区分大小写(当然,如果您需要的话)。

回答by Peter Gluck

This also works to replace anything not a digit, a word character, or a period with an underscore. Useful for filenames.

这也适用于用下划线替换不是数字、单词字符或句点的任何内容。对文件名有用。

$clean = preg_replace('/[^\d\w.]+/', '_', $string);