开发者

ONE question regular expression PHP

开发者 https://www.devze.com 2023-01-05 02:03 出处:网络
Count characte开发者_开发技巧r \'_\' in start line example : subject = \'_abcd_abc\';// return 1

Count characte开发者_开发技巧r '_' 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


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.

  • strspn()
  • ltrim()
  • strlen()


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消