【发布时间】: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