Home > Article > Backend Development > How to remove identical strings in php
Method: 1. Use "implode("",array_unique(str_split(string, 1)));" to remove the same string; 2. Use "implode("",array_unique(preg_split(regular expression , string)))" to remove identical strings.
Recommended: "PHP Video Tutorial"
php method to remove identical strings:
1. If there are no Chinese characters in the string and they are all ASCII characters, it is very simple:
<?php $str = 'aabbcc11333332.axyz'; echo implode("",array_unique(str_split($str, 1))); //输出 abc132.xyz
2 . If there are Chinese characters in the string and the encoding is UTF8, you can use the following method:
<?php $str="爱爱E爱EE族族"; $arr = preg_split("/(?<!^)(?!$)/u", $str); //转换成数组 $arr = array_unique($arr); //除去重复字符 echo implode("", $arr); //还原成字符串 //输出: 爱E族
3. If there are Chinese characters in the string and the encoding is not UTF8, you can use the following method (the encoding can be specified):
<?php //按长度分割含中文字符串的自定义函数 function mb_str_split($str, $length=1, $encoding='UTF-8') { $arr = array(); for($i=0; $i<mb_strlen($str, $encoding); $i+=$length) { $arr[] = mb_substr($str, $i, $length, $encoding); } return $arr; } $arr = mb_str_split("爱爱爱E族族", 1, 'GBK'); $arr = array_unique($arr); //除去重复字符 echo implode("", $arr); //还原成字符串 //输出: 爱E族
The above is the detailed content of How to remove identical strings in php. For more information, please follow other related articles on the PHP Chinese website!