从字符串中删除某些字符的重复项

问题描述:

仅在字符串$b中相邻时,如何才能从字符串$b中删除在数组$a中找到的重复字符?

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";

输出应为

abcdef

可以使用正则表达式找到字符,但是我不知道如何检测字符是否相邻.

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

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;