subject = $subject; $this->delim = $delim; // Micro-optimisation (theoretical) $this->subjectLength = strlen( $subject ); $this->delimLength = strlen( $delim ); $this->rewind(); } public function rewind() { $this->curPos = 0; $this->endPos = strpos( $this->subject, $this->delim ); $this->refreshCurrent(); } public function refreshCurrent() { if ( $this->curPos === false ) { $this->current = false; } elseif ( $this->curPos >= $this->subjectLength ) { $this->current = ''; } elseif ( $this->endPos === false ) { $this->current = substr( $this->subject, $this->curPos ); } else { $this->current = substr( $this->subject, $this->curPos, $this->endPos - $this->curPos ); } } public function current() { return $this->current; } /** * @return int|bool Current position or boolean false if invalid */ public function key() { return $this->curPos; } /** * @return string */ public function next() { if ( $this->endPos === false ) { $this->curPos = false; } else { $this->curPos = $this->endPos + $this->delimLength; if ( $this->curPos >= $this->subjectLength ) { $this->endPos = false; } else { $this->endPos = strpos( $this->subject, $this->delim, $this->curPos ); } } $this->refreshCurrent(); return $this->current; } /** * @return bool */ public function valid() { return $this->curPos !== false; } }