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

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

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

Disclosure: My content contains affiliate links.

43,695 questions

57,003 answers

573 users

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

1 Answer

0 votes
function split_and_keep(string $text, array $delims): array {
    if ($text === '') {
        return [];
    }

    $delimSet = array_flip($delims);  // fast lookup
    $result = [];
    $start = 0;
    $len = strlen($text);

    for ($i = 1; $i < $len; $i++) {
        $prev = $text[$i - 1];
        $curr = $text[$i];

        $prevIsDelim = isset($delimSet[$prev]);
        $currIsDelim = isset($delimSet[$curr]);

        $shouldSplit =
            ($prevIsDelim xor $currIsDelim) ||        // text ↔ delim
            ($prevIsDelim && $currIsDelim && $prev !== $curr); // delim type changed

        if ($shouldSplit) {
            $result[] = substr($text, $start, $i - $start);
            $start = $i;
        }
    }

    // Add final segment
    $result[] = substr($text, $start);

    return $result;
}

$s = "aa==bbb---cccc++++ddddd";
$delimiters = ["=", "-", "+"];

$parts = split_and_keep($s, $delimiters);

foreach ($parts as $p) {
    echo "[$p] ";
}



/*
run:

[aa] [==] [bbb] [---] [cccc] [++++] [ddddd] 

*/

 



answered Mar 10 by avibootz

Related questions

...