简体   繁体   English

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

[英]How to remove all non-alphanumeric and non-space characters from a string in PHP?

I want to remove all non-alphanumeric and space characters from a string. 我想从字符串中删除所有非字母数字和空格字符。 So I do want spaces to remain. 所以我确实希望留下空间。 What do I put for a space in the below function within the [ ] brackets: 我在[]括号中为下面的函数添加了什么空格:

ereg_replace("[^A-Za-z0-9]", "", $title);

In other words, what symbol represents space, I know \\n represents a new line, is there any such symbol for a single space. 换句话说,什么符号代表空间,我知道\\ n代表一个新的行,是否有任何这样的符号用于单个空格。

Just put a plain space into your character class: 只需在您的角色类中放置一个空格:

[^A-Za-z0-9 ]

For other whitespace characters (tabulator, line breaks, etc.) use \\s instead. 对于其他空格字符(制表符,换行符等),请使用\\s代替。

You should also be aware that the PHP's POSIX ERE regular expression functions are deprecated and will be removed in PHP 6 in favor of the PCRE regular expression functions . 您还应该知道PHP的POSIX ERE正则表达式函数已被弃用,并将在PHP 6中删除,以支持PCRE正则表达式函数 So I recommend you to use preg_replace instead: 所以我建议你改用preg_replace

preg_replace("/[^A-Za-z0-9 ]/", "", $title)

如果你只想要一个文字空间,就把它放进去。像'空白字符'那样的组,比如tab和换行符是\\ s

The accepted answer does not remove spaces. 接受的答案不会删除空格。

Consider the following 考虑以下

$string = 'tD  13827$2099';
$string = preg_replace("/[^A-Za-z0-9 ]/", "", $string);

echo $string;

> tD  138272099

Now if we str_replace spaces, we get the desired output 现在,如果我们str_replace空格,我们得到所需的输出

$string = 'tD  13827$2099';
$string = preg_replace("/[^A-Za-z0-9 ]/", "", $string);

// remove the spaces
$string = str_replace(" ", "", $string);

echo $string;

> tD138272099

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM