3v4l.org

run code in 300+ PHP versions simultaneously
<?php function modern_strtok(string $string, string $delim): \Generator { $pos = 0; while (true) { $pos += \strspn($string, $delim, $pos); $len = \strcspn($string, $delim, $pos); if (!$len) return; $delim = (yield \substr($string, $pos, $len)) ?? $delim; $pos += $len; } } $string = ' -- This -- is an example -string '; $delim = ' -'; foreach (modern_strtok($string, $delim) as $tok) { var_dump($tok); } echo "************\n"; // changing $delim mid-course for ($g = modern_strtok($string, $delim); $g->valid(); $g->send($delim)) { var_dump($g->current()); $delim = ' '; }

preferences:
16.24 ms | 411 KiB | 6 Q