2011-12-13 93 views
8

我想在一個字符串的開頭計數(在一個正則表達式中)所有空格。開始計算空白

我的想法:

$identSize = preg_match_all("/^()[^ ]/", $line, $matches); 

例如:

$example1 = " Foo"; // should return 1 
$example2 = " Bar"; // should return 2 
$example3 = " Foo bar"; // should return 3, not 4! 

任何提示,我怎麼能解決這個問題?

回答

14
$identSize = strlen($line)-strlen(ltrim($line)); 

或者,如果你想要的正則表達式,

preg_match('/^(\s+)/',$line,$matches); 
$identSize = strlen($matches[1]); 
+1

第一個是聰明的。我可以想象它比preg_match版本更快。 – Powertieke

+0

+1,但您的第一個版本只考慮空格,您可能還想包含其他空格字符。 – codaddict

+0

@codaddict雖然OP的問題是計算空格,所以如果有任何關於指定正則表達式的註釋。 –

1

你可以做連續的空格一個的preg_match在字符串的開頭(因此,它匹配的字符串返回「「)。

然後,您可以在匹配上使用strlen來返回空白字符的數量。

9

而不是使用正則表達式(或任何其他黑客),你應該使用strspn,它被定義爲處理這些類型的問題。

$a = array (" Foo", " Bar", " Foo Bar"); 

foreach ($a as $s1) 
    echo strspn ($s1, ' ') . " <- '$s1'\n"; 

輸出

1 <- ' Foo' 
2 <- ' Bar' 
3 <- ' Foo Bar' 

如果OP要數不僅僅空間(即其他白字)更多第二參數strspn應該" \t\r\n\0\x0B"(取自什麼trim定義爲白色字符)。

文檔PHP: strspn - Manual