PHP to remove duplicate string program code

Source: Internet
Author: User

Regular expressions

The code is as follows Copy Code

echo Preg_replace ("/([^s]+) *\1{2,} ([^s]+) * *", ", $string);


With the loop I wrote a


Example 1

The code is as follows Copy Code

$str = ' ABCCBA 9872223s 12121212 ddd 1234560 vbwwc asasasasas zxzx ';
$source _array = Explode ("", $str);
foreach ($source _array as $key => $item) {
$current _str = Str_split ($item, 1);
$current _array=array_count_values ($current _str);
foreach ($current _array as $k => $it) {
if ($it >=3)
unset ($source _array[$key]);
}
}
Var_dump ($source _array);

Example 2

  code is as follows copy code

<?php
$str = ' ant Ant College College, I Love love love Loves Love You!522200011111333311111444 ';
function Mbstringtoarray ($STR, $charset) {
  $strlen =mb_strlen ($STR);
  while ($strlen) {
     $array []=mb_substr ($str, 0,1, $charset);
    $str =mb_substr ($str, 1, $strlen, $charset);
    $strlen =mb_strlen ($STR);
 }
  return $array;
}
$arr = Mbstringtoarray ($str, "GBK"); //split string
$arr = Array_unique ($arr);           //Filter repeat character
$str = Implode (', $arr);            //merge array
Echo $str;


Another way

Preg_replace_callback () is simpler, but preg_replace () can use the E modifier to achieve preg_replace_eval, which can be achieved

Pretty much the effect.

The code is as follows Copy Code

echo preg_replace ('/([^s]+)/e ', ' Check (' \1 ') ', $string);
function Check ($STR) {
$tmp =count_chars ($STR, 1);
Sort ($tmp);
Return Array_pop ($tmp) >2? ": $str;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.