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 = ' '; }
Output for 8.1.0 - 8.1.29, 8.2.0 - 8.2.21, 8.3.0 - 8.3.9
string(4) "This" string(2) "is" string(2) "an" string(7) "example" string(6) "string" ************ string(4) "This" string(2) "--" string(2) "is" string(2) "an" string(7) "example" string(7) "-string"

preferences:
74.37 ms | 403 KiB | 67 Q