PHP删除或保存在一个字符串中的重复文字
程序员文章站
2022-06-03 11:43:29
...
这个类可以删除或保存在一个字符串中的重复文字。
并且可以删除第几个位置上的重复文字
并且可以删除第几个位置上的重复文字
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