【问题标题】:strpos() within while loop never endswhile 循环中的 strpos() 永远不会结束
【发布时间】:2014-12-23 22:14:20
【问题描述】:

有一个字符串,

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

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

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

所以,我尝试了#1:

$count = 0;

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

还有#2,

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

它们都不会结束。问题出在哪里?

【问题讨论】:

  • strpos() 不会改变 $string。每次迭代都会得到相同的结果。
  • 我知道它不能回答您的问题,但这可能是“问错问题”的情况之一。 Prasanth 和 Jack 都为您提供了计算这些逗号的“最佳”方法,您真的应该使用他们建议的方法来处理这些事情。

标签: php while-loop strpos


【解决方案1】:

你可以使用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);
}

【讨论】:

    【解决方案2】:

    strpos() 返回$needle 的第一次出现,因此除非您指定不同的$offset,否则您将始终得到相同的结果,因此是无限循环。

    如果你坚持使用strpos(),试试这个:

    $pos=0;
    while(($pos = strpos($string, ',',$pos)) !== FALSE){
        $count++;
        $pos++;
        // This ends
    }
    

    当然,您可以使用substr_count() 让事情变得更简单。

    编辑

    Live demo

    【讨论】:

      【解决方案3】:

      试试这个:

      $text = 'Foo, Bar, Test,';
      echo substr_count($text, ',');
      

      参考:http://php.net/manual/en/function.substr-count.php

      【讨论】:

        【解决方案4】:

        如果 substr_count 不合适,也可以试试这个:

        $pos = -1;
        $count=0;
        while( $pos = strpos($in, ',', $pos+1) !== FALSE){
             $count++;
             }
        

        我没有测试您是否绝对需要 !==FALSE。如果你使用 mb_strpos,你就不用。

        【讨论】:

          猜你喜欢
          • 2011-01-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-05-21
          • 1970-01-01
          • 2016-10-27
          相关资源
          最近更新 更多