while 循环中的 strpos() 永远不会结束

Yan*_*ang 4 php while-loop strpos

有一个字符串,

$string = 'Foo, Bar, Test,';

我想要做的就是计算字符串中逗号的数量。

但一切都会导致无限的 while 循环。

所以,我试过#1:

$count = 0;

while($pos = strpos($string, ',') !== FALSE){
    $count++;
    // Never ends
}
Run Code Online (Sandbox Code Playgroud)

还有#2,

while(true){
  if ( strpos($string, ',') !== FALSE ){
     $count++;
  } else {
    break;
  }
}
Run Code Online (Sandbox Code Playgroud)

他们俩永远不会结束。问题出在哪里?

Ja͢*_*͢ck 5

你可以使用substr_count()

substr_count($string, ',');
Run Code Online (Sandbox Code Playgroud)

在您的代码中,strpos()需要第三个参数才能从特定偏移量开始搜索,例如:

strpos($string, ',', 12); // start searching from index 12
Run Code Online (Sandbox Code Playgroud)

它不像迭代器那样工作。像这样的事情会起作用:

$start = 0;
while (($pos = strpos($string, ',', $start)) !== FALSE) {
  $count++;
  $start = $pos + 1;
}
Run Code Online (Sandbox Code Playgroud)

更新

如果你想获得真正的幻想:

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);
}
Run Code Online (Sandbox Code Playgroud)