How to replace consecutive characters with only one using RegEx in PHP

1 Answer

0 votes
function remove_consecutive_duplicates($input) {
    // Matches any character (.) followed by itself one or more times (\1+)
    $pattern = '/(.)\1+/';

    // Replaces with the first captured group
    $result = preg_replace($pattern, '$1', $input);
    
    return $result;
}

$input = "aaaabbbccdddddd";
$modified = remove_consecutive_duplicates($input);

echo "Original: $input\n";
echo "Modified: $modified\n";



/*
run:

Original: aaaabbbccdddddd
Modified: abcd

*/

 



answered Jun 6, 2025 by avibootz
...