php 替换除字母、数字、空格和下划线以外的所有字符

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

Replace all characters except letters, numbers, spaces and underscores

phpregexpreg-replaceereg-replace

提问by Daniel Blackmore

I am looking to replace all characters in a string except letters, numbers, spaces and underscores.

我希望替换字符串中除字母、数字、空格和下划线之外的所有字符。

Could someone please provide a example?

有人可以提供一个例子吗?

回答by jeroen

I normally use something like:

我通常使用类似的东西:

$string = preg_replace("/[^ \w]+/", "", $string);

That replaces all non-space and non-word characters with nothing.

这将用空替换所有非空格和非单词字符。

回答by Raffael

[^0-9a-zA-Z_\s] 

is what you want to replace.

是你想要更换的。

回答by agent-j

<?php
$string = 'April 15, 2003';
$pattern = '/[^\w ]+/';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);
?>