stef
stef

Reputation: 27749

Remove duplicates of certain characters from string

How could I remove duplicates of characters found in array $a from string $b only if they are found next to each other?

$a = array("a","b","c");
$b = "aabcccdef";

Output should be

abcdef

Characters can be found with a regex but I have no idea how to detect if the characters are next to each other.

Upvotes: 1

Views: 3003

Answers (3)

dynamic
dynamic

Reputation: 48091

preg_replace( array('/a+/','/b+/','/c+/'),array('a','b','c',), $b );

Another way pretty more elaborate could be:

preg_replace_callback('/(\w+)/', function ($matches) use ($a) {

   if ( in_array($matches[1][0],$a) )  //> if you need UTF-8 working use mb_substr here
    return $matches[1][0];

},$b);

//> both untested

Another way, old way (that could be a bit faster on few chars string):

$c = '';
$cache = false;
for ($i=0;$i<strlen($b);$i++) {
  $char = $b[$i];

  if ($char !== $cache || !in_array($char,$a)) 
   $c .= $char;

  $cache=$char;
}
echo $c;

Upvotes: 3

Felix Kling
Felix Kling

Reputation: 816364

Another way:

$expression = join('|', $a);
$b = preg_replace('/(' . $expression . ')\1+/', '$1', $b);

DEMO

Explanation:

The generated expression will look like (a|b)\1+, where a|b matches either a or b. \1 matches whatever was matched by the first capture group (a|b). This is how you can match a set of repeating characters. The match then gets replaced by the content of the capture group ($1).

This would not only work with single characters but with any substrings.

If the strings can contain special regular expression characters, you should escape those characters first (array_map('preg_quote', $a) should work just fine).

Upvotes: 1

Vitamin
Vitamin

Reputation: 1526

<?php
$a = array('a', 'b', 'c');
$b = 'aabcccdef';
$c = '';
for($i = 0; $i < strlen($b); $i++) {
    if(in_array($b[$i], $a) && (substr($c, -1) === $b[$i])) {
        continue;
    }
    $c .= $b[$i];
}
echo $c;

Upvotes: 0

Related Questions