<?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.30, 8.2.0 - 8.2.25, 8.3.0 - 8.3.14
- 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:
57.14 ms | 406 KiB | 5 Q