从字符串中删除某些字符的重复项 [英] Remove duplicates of certain characters from string

查看:70
本文介绍了从字符串中删除某些字符的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅在字符串$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;

这篇关于从字符串中删除某些字符的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆