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,181 questions

56,073 answers

573 users

How to remove duplicate words separated by multiple delimiters from a string in PHP

1 Answer

0 votes
/**
 * removeDuplicatesMultiDelimiter
 *
 * Removes duplicate items from a string using multiple delimiters.
 * Uses preg_split to break the string by ANY of the provided delimiters.
 *
 * @param string $s            The input string.
 * @param array  $delimiters   List of delimiters, e.g. [",", "|", ";"]
 * @return string              Cleaned string with duplicates removed,
 *                             rejoined using the FIRST delimiter.
 */
function removeDuplicatesMultiDelimiter(string $s, array $delimiters): string
{
    // Build a regex character class from delimiters
    // Example: [,\|;]  → splits on comma, pipe, semicolon
    $escaped = array_map('preg_quote', $delimiters);
    $pattern = '/[' . implode('', $escaped) . ']+/';

    // Split using ANY delimiter
    $parts = preg_split($pattern, $s, -1, PREG_SPLIT_NO_EMPTY);

    // Remove duplicates while preserving order
    $unique = array_unique($parts);

    // Reassemble using the FIRST delimiter
    return implode($delimiters[0], $unique);
}

// Main
$s = "AAA|aaa,aAA;aaA|AAa,AAA;BBB|CCC,AAA;AAA,aaa|aaa";

// Run the function with multiple delimiters
$result = removeDuplicatesMultiDelimiter($s, [",", "|", ";"]);

echo $result;


/*
run:

AAA,aaa,aAA,aaA,AAa,BBB,CCC

*/

 



answered Aug 1 by avibootz

Related questions

...