你可以只使用substr_count()
:
substr_count($string, ',');
在你的代码,strpos()
需要第三个参数,开始从一个特定的搜索补偿,例如:
strpos($string, ',', 12); // start searching from index 12
它不喜欢的工作一个迭代器。像这样的东西会工作:
$start = 0;
while (($pos = strpos($string, ',', $start)) !== FALSE) {
$count++;
$start = $pos + 1;
}
更新
如果你想获得真正看中的:
class IndexOfIterator implements Iterator
{
private $haystack;
private $needle;
private $start;
private $pos;
private $len;
private $key;
public function __construct($haystack, $needle, $start = 0)
{
$this->haystack = $haystack;
$this->needle = $needle;
$this->start = $start;
}
public function rewind()
{
$this->search($this->start);
$this->key = 0;
}
public function valid()
{
return $this->pos !== false;
}
public function next()
{
$this->search($this->pos + 1);
++$this->key;
}
public function current()
{
return $this->pos;
}
public function key()
{
return $this->key;
}
private function search($pos)
{
$this->pos = strpos($this->haystack, $this->needle, $pos);
}
}
foreach (new IndexOfIterator($string, ',') as $match) {
var_dump($match);
}
'strpos()'不会改变'$ string'。每次迭代你都会得到相同的结果。 – dirn 2013-02-18 06:58:57
我知道它并不回答你的问题,但这可能是其中一个“问错问题”的情况。 Prasanth和Jack都给你提供了“最好”的方法来计算这些逗号,你真的应该使用他们建议的方法来处理这些事情。 – Stuart 2013-02-18 07:01:04