龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > php编程 >

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

时间:2014-07-22 14:48来源: 作者: 点击:
分享到:
这个类可以删除或保存在一个字符串中的重复文字。并且可以删除第几个位置上的重复文字
这个类可以删除或保存在一个字符串中的重复文字。

并且可以删除第几个位置上的重复文字
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. [代码]使用方法     跳至 [1] [2] [全屏预览]

//呵呵以网站域名为例(顺便打个小广告)
$contents ='http://www.codepearl.com codepearl codepearl.com wwww.codepearl.com';
 
$StringRemoveDuplicates = new StringClean;
 
$contents = $StringRemoveDuplicates->keep_nth('codepearl', $contents,"", 2); 
 
var_dump($contents );  
//输出:http://www.codepearl.com codepearl.com wwww.codepearl.com
精彩图集

赞助商链接