• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

406
Views
How to remove duplicate words from string using php?

Below is the variable I have,

$string = 'AAA,BBB,aAA,BbB,AAA,BbB';

I need the unique string result below,

$string = 'AAA,BBB,aAA,BbB';

How to make it unique just like array_unique() function , is there any default String function to remove duplicate string in PHP?

about 3 years ago · Santiago Trujillo
2 answers
Answer question

0

I don't know if php have such function, but you can process it like this: live demo

$raw = 'AAA,BBB,aAA,BbB,AAA,BbB';
$string = implode(',', array_unique(explode(',', $raw)));
about 3 years ago · Santiago Trujillo Report

0

For the record, I fully support Kris' method, and that is the way I would choose if this were for my project. However, I would just like to add that there are several additional ways to skin this cat:

Code: (Demo)

$raw = 'AAA,BBB,aAA,BbB,BbB,AAA';

// str_word_count() -> array_unique() -> implode()
echo implode(',',array_unique(str_word_count($raw,1)));
echo "\n";

// str_getcsv() -> array_unique() -> implode()
echo implode(',',array_unique(str_getcsv($raw)));
echo "\n";

// preg_match_all() -> array_unique() -> join()
echo join(',',array_unique(preg_match_all("/[A-Za-z]{3}/",$raw,$m)?$m[0]:array()));
echo "\n";

// preg_split() -> array_unique() -> join()
echo join(',',array_unique(preg_split("/,/",$raw)));
echo "\n";

// preg_replace() -> parse_str() -> implode()
parse_str(preg_replace('/(^|,)([A-Za-z]{3})/',"$2=$2&",$raw),$array);
echo implode(',',$array);

I have 5 different methods to explode the csv string without using explode().

1 method that doesn't use array_unique.

And of course implode() and join() can be used interchangeably as they are synonyms.

I think the fifth method is my favorite as it is the wackiest and doesn't use array_unique(). *unfortunately it's a two-liner :{


p.s.

@Thiyagu says this is how the string is constructed:

forloop(){ $string .= $a[i].',';}

If that is true, then weeding out the duplicates can be done inside this loop by leveraging a temporary array. This has the added benefit of omitting the trailing comma that concatenation generates.

foreach($data as $value){
    $result[$value]=$value;  // duplicate values will be overwritten because arrays may not have two identical keys
}
echo implode(',',$result);
about 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error