2011-12-13 95 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