php while结束循环吗,php – strpos()在while循环中永远不会结束

有一个字符串,

$string = ‘Foo, Bar, Test,’;

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

但是一切都会导致无限循环.

所以,我试过#1:

$count = 0;

while($pos = strpos($string, ',') !== FALSE){

$count++;

// Never ends

}

还有#2,

while(true){

if ( strpos($string, ',') !== FALSE ){

$count++;

} else {

break;

}

}

他们都没有结束.哪里有问题?

解决方法:

你可以使用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,php,while-loop

来源: https://codeday.me/bug/20190725/1535585.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值