note 103961 added to function.strtok
| From: | Anonymous at osu1 dot php dot net | Date: | Fri, 13 May 2011 19:10:29 +0000 |
| Subject: | note 103961 added to function.strtok | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-179702@lists.php.net to get a copy of this message | ||
Here's a simple class that allows you to iterate through string tokens using a foreach loop.
<?php
/**
* The TokenIterator class allows you to iterate through string tokens using
* the familiar foreach control structure.
*
* Example:
* <code>
* <?php
* $string = 'This is a test.';
* $delimiters = ' ';
* $ti = new TokenIterator($string, $delimiters);
*
* foreach ($ti as $count => $token) {
* echo sprintf("%d, %s\n", $count, $token);
* }
*
* // Prints the following output:
* // 0. This
* // 1. is
* // 2. a
* // 3. test.
* </code>
*/
class TokenIterator implements Iterator
{
/**
* The string to tokenize.
* @var string
*/
protected $_string;
/**
* The token delimiters.
* @var string
*/
protected $_delims;
/**
* Stores the current token.
* @var mixed
*/
protected $_token;
/**
* Internal token counter.
* @var int
*/
protected $_counter = 0;
/**
* Constructor.
*
* @param string $string The string to tokenize.
* @param string $delims The token delimiters.
*/
public function __construct($string, $delims)
{
$this->_string = $string;
$this->_delims = $delims;
$this->_token = strtok($string, $delims);
}
/**
* @see Iterator::current()
*/
public function current()
{
return $this->_token;
}
/**
* @see Iterator::key()
*/
public function key()
{
return $this->_counter;
}
/**
* @see Iterator::next()
*/
public function next()
{
$this->_token = strtok($this->_delims);
if ($this->valid()) {
++$this->_counter;
}
}
/**
* @see Iterator::rewind()
*/
public function rewind()
{
$this->_counter = 0;
$this->_token = strtok($this->_string, $this->_delims);
}
/**
* @see Iterator::valid()
*/
public function valid()
{
return $this->_token !== FALSE;
}
}
----
Server IP: 192.41.42.26
Probable Submitter: 12.153.215.194
----
Manual Page -- http://www.php.net/manual/en/function.strtok.php
Edit -- https://master.php.net/note/edit/103961
Del: integrated -- https://master.php.net/note/delete/103961/integrated
Del: useless -- https://master.php.net/note/delete/103961/useless
Del: bad code -- https://master.php.net/note/delete/103961/bad+code
Del: spam -- https://master.php.net/note/delete/103961/spam
Del: non-english -- https://master.php.net/note/delete/103961/non-english
Del: in docs -- https://master.php.net/note/delete/103961/in+docs
Del: other reasons-- https://master.php.net/note/delete/103961
Reject -- https://master.php.net/note/reject/103961
Search -- https://master.php.net/manage/user-notes.php