Home >Backend Development >PHP Tutorial >How to remove duplicate numbers or characters from string in php

How to remove duplicate numbers or characters from string in php

王林
王林Original
2019-12-02 11:05:402731browse

How to remove duplicate numbers or characters from string in php

Use php to delete repeated characters in the string.

For example: $str = "aaadddd"The final result should be "ad".

Idea:

Traverse the entire array, then take out the i-th character in turn, store it in a temporary array, and traverse the temporary array at the same time to find out whether the array is already This character exists.

Related learning video recommendations: php video tutorial

The code is as follows:

$b = 'aaaaaaaaaaaaddddddttttttffff';  
$tmp = array();  
for($i = 0; $i < strlen($b); $i++){      
    $len = count($tmp);          
    for($j = 0; $j < $len; $j++){          
        if($b[$i] === $tmp[$j]){             
            break;          
        }      
    }      
if($j == $len){  //如果最后的$j和$len相等的话,则表示$tmp临时数组中不存在$b[$i]          
    $tmp[] = $b[$i];      
}  
}  
$result = implode($tmp);  
//输出adtf

Related article tutorial recommendations: php basic tutorial

The above is the detailed content of How to remove duplicate numbers or characters from string in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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