繁体   English   中英

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

[英]How do I compress space characters with PHP regular expressions?

$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
$foo = preg_replace("/[^a-zA-Z0-9\s]/", "", $string);
$foo = preg_replace('/\s+/',' ',$foo);

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

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

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

s/\s+/ /g

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

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

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

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

全局替换( 编辑测试):

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

用“”

暂无
暂无

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

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