计算开始的空格

Xov*_*ver 8 php regex

我想计算(在单个正则表达式中)字符串开头的所有空格.

我的想法:

$identSize = preg_match_all("/^( )[^ ]/", $line, $matches);
Run Code Online (Sandbox Code Playgroud)

例如:

$example1 = " Foo"; // should return 1
$example2 = "  Bar"; // should return 2
$example3 = "   Foo bar"; // should return 3, not 4!
Run Code Online (Sandbox Code Playgroud)

任何提示,我如何解决它?

Tim*_*mur 16

$identSize = strlen($line)-strlen(ltrim($line));
Run Code Online (Sandbox Code Playgroud)

或者,如果你想要正则表达式,

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


Fil*_*efp 11

您应该使用strspn,而不是使用正则表达式(或任何其他黑客),它被定义为处理这些类型的问题.

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

foreach ($a as $s1)
  echo strspn ($s1, ' ') . " <- '$s1'\n";
Run Code Online (Sandbox Code Playgroud)

产量

1 <- ' Foo'
2 <- '  Bar'
3 <- '   Foo Bar'
Run Code Online (Sandbox Code Playgroud)

如果OP想要计算的不仅仅是空格(即其他白色字符),那么第二个参数strspn应该是" \t\r\n\0\x0B"(取自trim定义为白色字符的那个).

文档PHP:strspn - 手册