tags:

views:

56

answers:

2

Count character '_' in start line

example :

subject = '_abcd_abc';   // return 1
or 
subject = '__abcd_abc';  // return 2
or 
subject = '___abcd_abc';  // return 3

everyone help me ~ I use PHP

+1  A: 

Try this:

return preg_match('/^_+/', $str, $match) ? strlen($match[0]) : 0;

If preg_match finds a match, $match[0] will contain that match and strlen($match[0]) returns the length of the match; otherwise the expression will return 0.

Gumbo
preg_match stops searching after the first match is found.
Peter Ajtai
@Peter Ajtai: So?
Gumbo
Whoops, I thought he wanted the total number of underscores used in the whole string. Never mind, I see.
Peter Ajtai
@Peter Ajtai: Apparently he/she is just looking for the number of leading characters.
Gumbo
@Gumbo Yeah. I just didn't realize what they were after.
Peter Ajtai
+3  A: 

If you are sure the start of the string contains _, you can do this with just strspn():

echo strspn('___abcd_abc',  '_');
// -> 3

If there might be no leading underscores, you can still do this without a regex using strlen and ltrim:

strlen($str) - strlen(ltrim($str, "_"));

This counts the string length, then subtracts the string length without the underscores on the left, the result being the number of underscores.

Andy E