php 使用 preg_replace 删除所有非字母数字字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11321048/
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:16:42  来源:igfitidea点击:

Remove all non-alphanumeric characters using preg_replace

phpregexpreg-replace

提问by lisovaccaro

How can I remove all non alphanumeric characters from a string in PHP?

如何从 PHP 中的字符串中删除所有非字母数字字符?

This is the code, that I'm currently using:

这是我目前正在使用的代码:

$url = preg_replace('/\s+/', '', $string);

It only replaces blank spaces.

它只替换空格。

回答by John Conde

$url = preg_replace('/[^\da-z]/i', '', $string);

回答by sevenadrian

At first take this is how I'd do it

起初,这就是我要做的

$str = 'qwerty!@#$@#$^@#$Hello%#$';

$outcome = preg_replace("/[^a-zA-Z0-9]/", "", $str);

var_dump($outcome);
//string(11) "qwertyHello"

Hope this helps!

希望这可以帮助!

回答by Chuck Le Butt

Not sure why no-one else has suggested this, but this seems to be the simplest regex:

不知道为什么没有其他人提出这个建议,但这似乎是最简单的正则表达式:

preg_replace("/\W|_/", "", $string)

You can see it in action here, too: http://phpfiddle.org/lite/code/0sg-314

你也可以在这里看到它的实际效果:http: //phpfiddle.org/lite/code/0sg-314

回答by Damith Ruwan

You can use,

您可以使用,

$url = preg_replace('/[^\da-z]/i', '', $string);

You can use for unicode characters,

您可以使用 unicode 字符,

$url = preg_replace("/[^[:alnum:][:space:]]/u", '', $string);

回答by lisovaccaro

preg_replace('/[\s\W]+/', '', $string)

Seems to work, actually the example was in PHP documentation on preg_replace

似乎有效,实际上该示例在 preg_replace 的 PHP 文档中

回答by Alix Axel

$alpha = '0-9a-z'; // what to KEEP
$regex = sprintf('~[^%s]++~i', preg_quote($alpha, '~')); // case insensitive

$string = preg_replace($regex, '', $string);