- substr: documentation ( source)
- strcspn: documentation ( source)
- var_dump: documentation ( source)
- strspn: documentation ( source)
<?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 = ' ';
}