2010-08-28 53 views

回答

2

您可以使用正则表达式:

$regex = '~\s{2,}~'; 
preg_match($regex, $str); 

\s包括空格,制表符和新行。如果你想只是空间,你可以改变$regex到:

$regex = '~ {2,}~'; 

如果你想从一个字符串中删除多余的空格,你可以使用:

$str = 'hello there, world!'; 

$regex = '~ {2,}~'; 
$str = preg_replace($regex, ' ', $str); 

echo $str; 

输出:

hello there, world! 
+0

+1相关:我喜欢波浪线。 – BoltClock 2010-08-28 02:31:56

+0

@Bolt我使用痣,有时感叹号。我从来没有使用正斜杠=/ – NullUserException 2010-08-28 02:33:50

+0

当我们在如此多的检查中每天都在匹配正斜杠时,它绝对会令人恶心:/ – BoltClock 2010-08-28 02:36:38

0

您可以使用:

$input = "foo bar baz saz"; 
if(preg_match_all('/\s{2,}/',$input,$matches)) { 
    var_dump($matches); 
} 

输出:

array(1) { 
    [0]=> 
    array(2) { 
    [0]=> 
    string(2) " " 
    [1]=> 
    string(3) " " 
    } 
} 

\s代表白色空间,其中包括空间,垂直标签,横片,返回滑架,新的行,换页。

如果你想匹配只是正常的空间,你可以使用正则表达式:

if(preg_match_all('/ {2,}/',$input,$matches)) {