I am looking to replace all characters in a string except letters, numbers, spaces and underscores.
我希望替换字符串中除字母、数字、空格和下划线之外的所有字符。
Could someone please provide a example?
有人能举个例子吗?
3 个解决方案
#1
68
I normally use something like:
我通常使用如下内容:
$string = preg_replace("/[^ \w]+/", "", $string);
That replaces all non-space and non-word characters with nothing.
它将所有非空格和非字字符替换为零。
#2
22
[^0-9a-zA-Z_\s]
is what you want to replace.
是你想要取代的。
#3
6
<?php
$string = 'April 15, 2003';
$pattern = '/[^\w ]+/';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);
?>
#1
68
I normally use something like:
我通常使用如下内容:
$string = preg_replace("/[^ \w]+/", "", $string);
That replaces all non-space and non-word characters with nothing.
它将所有非空格和非字字符替换为零。
#2
22
[^0-9a-zA-Z_\s]
is what you want to replace.
是你想要取代的。
#3
6
<?php
$string = 'April 15, 2003';
$pattern = '/[^\w ]+/';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);
?>