meotimdihia
meotimdihia

Reputation: 4299

ONE question regular expression PHP

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

Upvotes: 1

Views: 83

Answers (2)

Andy E
Andy E

Reputation: 344585

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.

Upvotes: 3

Gumbo
Gumbo

Reputation: 655309

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.

Upvotes: 1

Related Questions