How should I count the number of occurrences of a character at the beginning of a string in PHP

StackOverflow https://stackoverflow.com/questions/441581

  •  22-07-2019
  •  | 
  •  

Question

The best that I have been able to come up with is:

strlen(preg_replace('/^([\\*]*)\s(.+)/',"$1",$line));
^^That seems to give the length of the string.^^

edit: I think that I should clarify that the character that I am trying to find is '*'

Was it helpful?

Solution

preg_match allows an output parameter which is filled with the matches, thus you can simply take the strlen of the match for the pattern /^**/:

$matches = array();
preg_match("/^\**/", $string, $matches);
$result =  strlen($matches[0]) ;

...

"***Hello world!*" -> 3
"Hello world!" -> 0

OTHER TIPS

This is a little wonky but it might work--it counts the number of times the first character is repeated:

strlen($line) - strlen(ltrim($line, $line[0]));

If you just want to remove all the stars from beginning, then this is a little easier

strlen($line) - strlen(ltrim($line, '*'));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top