php - strpos() within while loop never ends -



php - strpos() within while loop never ends -

there's string,

$string = 'foo, bar, test,';

all want count number of commas within string.

but leads infinite while loop.

so, i've tried #1:

$count = 0;

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

and #2,

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

they both never end. where's problem?

you utilize substr_count():

substr_count($string, ',');

in code, strpos() requires 3rd parameter start searching particular offset, e.g.:

strpos($string, ',', 12); // start searching index 12

it doesn't work iterator. work:

$start = 0; while (($pos = strpos($string, ',', $start)) !== false) { $count++; $start = $pos + 1; }

update

if want real fancy:

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() { homecoming $this->pos !== false; } public function next() { $this->search($this->pos + 1); ++$this->key; } public function current() { homecoming $this->pos; } public function key() { homecoming $this->key; } private function search($pos) { $this->pos = strpos($this->haystack, $this->needle, $pos); } } foreach (new indexofiterator($string, ',') $match) { var_dump($match); }

php while-loop strpos

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -