如何使用PHP正则表达式压缩空格字符?

时间:2011-03-24 01:04:10

标签: php regex

$string = 'Hello    this is a bunch of numbers: 333 and letters and $pecial Characters@!*(';

$foo = preg_replace("/[^a-zA-Z0-9\s]/", "", $string);

echo $foo;

以上回报:

Hello    this is a bunch of numbers 333 and letters and pecial Characters

我想保留空格,但如果不止一个,我想保留空格。怎么办?

应该看起来像:

Hello this is a bunch of numbers 333 and letters and pecial Characters

4 个答案:

答案 0 :(得分:5)

$foo = preg_replace("/[^a-zA-Z0-9\s]/", "", $string);
$foo = preg_replace('/\s+/',' ',$foo);

答案 1 :(得分:2)

一个正则表达式会这样做:

$foo = preg_replace('/[^a-zA-Z0-9\s]|(\s)\s+/', '$1', $string);

答案 2 :(得分:1)

我没有使用PHP,但是在Perl中它是这样的:

s/\s+/ /g

即。用一个空格替换一个或多个空格的任何序列。

所以我想象压缩空格的PHP将是:

$foo = preg_replace("/\s{2,}/", " ", $string);

我认为运行两个preg_replace行不会有任何问题,特别是如果它使代码更清晰。

答案 3 :(得分:0)

全局替换(编辑 - 已测试):

/(?<=\s)\s+|[^a-zA-Z0-9\s]+/

用“”