php regex how to remove duplicate charactors and make every charactor unique in string

198

How should one usepreg_replace() to replace a string from 'aabbaacc' to 'abc'?

Currently, my code usesstr_split() thenarray_unique() thenimplode(). I thinkpreg_replace() can achieve this also, but I don't know how.

Thank you for your help.

719

Answer

Solution:

A regex that seems to work for me is/(.)(?=.*?\1)/. Please test it for yourself here:

http://regexpal.com/

I've also tested it withpreg_replace('/(.)(?=.*?\1)/', '', 'aaabbbabc') which returns the expectedabc.

Hope this helps :)

936

Answer

Solution:

This is the closest I got. However, it's basically a copy of : How do I remove duplicate characters and keep the unique one only in Perl?

<?php
    $string = 'aabbaacc';

    $new = preg_replace( '/(.)(?=.*?\1)/i','', $string  );

    echo $new;
?>

Unfortunately, it does not keep the string in the same order. I don't know if that is important to you or not.

564

Answer

Solution:

try this

$string = 'dbbaabbbaac';

$new = preg_replace_callback( array("/(.)\\1+/"),function($M){print_r($M);return $M[1];}, $string  );
$new = preg_replace_callback( array('/(.)(.?\\1)/i','/(.)(.*?\\1)/i'),function($M){return $M[1].trim($M[2],$M[1]);}, $new  );
echo $new."\n";

output

dbac

or this with out Regex

$value="aabbaacc";
for($i=0;$i<strlen($value);$i++){
    $out[$value[$i]]=$value[$i];
}
echo implode("",$out);

output:

abc

People are also looking for solutions to the problem: PHP writing a text file in the begin

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.