Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,393 questions

52,502 answers

573 users

How to split a string on multiple single‑character delimiters (and keep them) in PHP

1 Answer

0 votes
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] 

*/

 



answered Mar 9 by avibootz

Related questions

...