Here is the iterator approach:
class SubstringIterator extends IteratorIterator { protected $startAtOffset, $endAtOffset; public function __construct($iterator, $startAtOffset, $endAtOffset = null) { parent::__construct($iterator); $this->startAtOffset = $startAtOffset; $this->endAtOffset = $endAtOffset; } public function current() { return substr(parent::current(), $this->startAtOffset, $this->endAtOffset); } }
You would use it as follows:
$playerIterator = new LimitIterator( new SubstringIterator( new SplFileObject('yourFile.txt'), 0, // start at beginning of line 15 // end before Alive: ) , 1 // start at line 2 in file (omits the headline) );
Then you can foreach on an iterator, for example.
foreach ($playerIterator as $player) { echo $player, PHP_EOL; }
Output:
player1 bug name with space bob
Or convert the folded iterators to an array:
$array = iterator_to_array($playerIterator); print_r($array);
Output:
Array ( [1] => player1 [2] => bug [3] => name with space [4] => bob )
Demo of the above examples with your file data
source share