2013-02-18 187 views
3

有一个字符串,strpos()内,而循环永远不会结束

$字符串= '富,酒吧,测试';

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

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

所以,我已经试过#1:

$计数= 0;

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

而且还#2,

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

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

+0

'strpos()'不会改变'$ string'。每次迭代你都会得到相同的结果。 – dirn 2013-02-18 06:58:57

+0

我知道它并不回答你的问题,但这可能是其中一个“问错问题”的情况。 Prasanth和Jack都给你提供了“最好”的方法来计算这些逗号,你真的应该使用他们建议的方法来处理这些事情。 – Stuart 2013-02-18 07:01:04

回答

4

你可以只使用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

0

或者试试这个,如果substr_count不适合:

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

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