开发者

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.


Just put a plain space into your character class:

[^A-Za-z0-9 ]

For other whitespace characters (tabulator, line breaks, etc.) use \s instead.

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. So I recommend you to use preg_replace instead:

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


If you want only a literal space, put one in. the group for 'whitespace characters' like tab and newlines is \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

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

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

echo $string;

> tD138272099
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜