2010-08-28 78 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)) {