2009-01-14 26 views
0

,我已经能够拿出的最好的是:我应该怎样算一个字符出现的次数在字符串中PHP开始

strlen(preg_replace('/^([\\*]*)\s(.+)/',"$1",$line));
^^这似乎给长度。字符串

编辑的^^:我想我应该澄清的是,我试图找到一个字符是“*”

+0

因为他SA在复制中标识它(http://stackoverflow.com/questions/441582/how-should-i-count-the-number-of-occurrences-of-a-character-at-the-beginning-of-a) 。这个1是第一个已经有1个答案,所以我标记了另一个答案。 – 2009-01-14 01:45:38

回答

3

的preg_match允许其充满相匹配的输出参数,因此,你可以简单地采取的strlen的比赛的模式/^** /:

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

...

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

这是一个有点靠不住,但它可能工作 - 它计数数第一个字符重复的次数:

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

如果你只是想删除所有从开始的星星,那么这是一个更容易一些

strlen($line) - strlen(ltrim($line, '*')); 
相关问题