function split_keep_delims(string $s, string $delimiters): array
{
$result = [];
// Build regex: e.g. ",;|" → "([,;|])"
$pattern = '/([' . preg_quote($delimiters, '/') . '])/';
// Find all delimiters with positions
preg_match_all($pattern, $s, $matches, PREG_OFFSET_CAPTURE);
$lastEnd = 0;
foreach ($matches[0] as $match) {
[$delim, $index] = $match;
// Add text before delimiter
if ($index > $lastEnd) {
$result[] = substr($s, $lastEnd, $index - $lastEnd);
}
// Add the delimiter itself
$result[] = $delim;
$lastEnd = $index + strlen($delim);
}
// Add remaining text after last delimiter
if ($lastEnd < strlen($s)) {
$result[] = substr($s, $lastEnd);
}
return $result;
}
$parts = split_keep_delims("aa,bbb;cccc|ddddd", ",;|");
foreach ($parts as $p) {
echo "[$p] ";
}
/*
run:
[aa] [,] [bbb] [;] [cccc] [|] [ddddd]
*/