Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting beginning whitespaces

Tags:

regex

php

I want to count (within a single regular expression) all spaces at the beginning of a string.

My ideas:

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

For example:

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

Any tips, how I can resolve it?

like image 422
Xover Avatar asked Dec 13 '11 09:12

Xover


2 Answers

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

Or, if you want regular expression,

preg_match('/^(\s+)/',$line,$matches);
$identSize = strlen($matches[1]);
like image 77
Timur Avatar answered Sep 29 '22 01:09

Timur


Instead of using a regular expression (or any other hack) you should use strspn, which is defined to handle these kinds of problems.

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

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

output

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

If OP wants to count more than just spaces (ie. other white characters) the 2nd argument to strspn should be " \t\r\n\0\x0B" (taken from what trim defines as white characters).

Documentation PHP: strspn - Manual

like image 37
Filip Roséen - refp Avatar answered Sep 29 '22 00:09

Filip Roséen - refp