Open In App

PHP Program to Print All Duplicate Characters in a String

Last Updated : 08 Jul, 2024
Comments
Improve
Suggest changes
24 Likes
Like
Report

This article will show you how to print duplicate characters in a string using PHP. Detecting and printing duplicate characters in a string is a common task in programming. In this article, we will explore various approaches to achieve this.

Using array_count_values() Function

The array_count_values() function is used to count the occurrences of each value in an array, simplifying the process.


Output
Duplicate characters: e o   G k s 

Using Associative Array

One of the most basic methods is to use an associative array to keep track of the occurrence of each character in the string.


Output
Duplicate characters: e o   G k s 

Using a Regular Expression and preg_match_all()

Another approach to print duplicate characters in a string is by using a regular expression in combination with the preg_match_all() function. This method is particularly useful for efficiently identifying and handling characters within the string.

Example: This approach offers a better way to detect and print duplicate characters in a string, especially when dealing with Unicode characters or requiring efficient pattern matching.


Output
Character 'r' appears 2 times.
Character 'g' appears 2 times.
Character 'm' appears 2 times.



Next Article

Similar Reads