How to remove duplicate numbers or characters from string in php

王林
Release: 2023-04-07 21:18:02
Original
2670 people have browsed it

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

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!

Related labels:
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