How to remove identical strings in php

藏色散人
Release: 2023-03-05 17:22:02
Original
2789 people have browsed it

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.

How to remove identical strings in php

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 = &#39;aabbcc11333332.axyz&#39;;
echo implode("",array_unique(str_split($str, 1)));
//输出 abc132.xyz
Copy after login

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族
Copy after login

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=&#39;UTF-8&#39;) {
    $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, &#39;GBK&#39;);
$arr = array_unique($arr); //除去重复字符
echo implode("", $arr);  //还原成字符串
//输出: 爱E族
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template