Home >php教程 >PHP源码 >PHP删除或保存在一个字符串中的重复文字

PHP删除或保存在一个字符串中的重复文字

PHP中文网
PHP中文网Original
2016-05-25 17:01:141352browse

这个类可以删除或保存在一个字符串中的重复文字。
并且可以删除第几个位置上的重复文字

1.处理类

class StringClean{
      
    public function keep_nth($string, $subject, $replacement='|CLEANUP|',  $nth=1){
          
        $contents      = $this->replace_nth($string, $subject,$replacement,  $nth);
  
        $contents      = str_replace($replacement,$string,$contents);
          
        return $contents;
    }
      
    public function replace_nth($string, $subject, $replacement='', $nth=1){
          
        $regExPattern = "/".preg_quote($string, '/')."/";
          
        return preg_replace_callback($regExPattern,
            function($found) use (&$regExPattern, &$replacement, &$nth) {
                    $nth--;
                    if ($nth==0) return preg_replace($regExPattern, $replacement, reset($found) );
                    return reset($found);
            }, $subject,$nth  );
    }
      
}

2.使用方法

//呵呵以网站域名为例(顺便打个小广告)
$contents ='http://www.php.cn';
  
$StringRemoveDuplicates = new StringClean;
  
$contents = $StringRemoveDuplicates->keep_nth('codepearl', $contents,"", 2); 
  
var_dump($contents );  
//输出:http://www.php.cn
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn