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?
$identSize = strlen($line)-strlen(ltrim($line));
Or, if you want regular expression,
preg_match('/^(\s+)/',$line,$matches);
$identSize = strlen($matches[1]);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With