简体   繁体   中英

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

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM