How to remove duplicate words separated by a custom delimiter from a string in PHP

1 Answer

0 votes
/**
 * removeDuplicates
 *
 * Removes duplicate items from a string using ANY delimiter.
 * This generalizes the explode → array_unique → implode pattern.
 *
 * @param string $s         The input string.
 * @param string $delimiter The delimiter used to separate items.
 * @return string           The cleaned string with duplicates removed.
 */
function removeDuplicates(string $s, string $delimiter): string
{
    // Split the string using the chosen delimiter
    $parts = explode($delimiter, $s);

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

    // Reassemble using the same delimiter
    return implode($delimiter, $unique);
}

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

// Run the function with a custom delimiter
$result = removeDuplicates($s, "|");

echo $result;


/*
run:

AAA|aaa|aAA|aaA|AAa|BBB|CCC

*/

 



answered Nov 16, 2017 by avibootz
edited Aug 1 by avibootz

Related questions

1 answer 174 views
1 answer 172 views
...