Search code examples
phpdnsstr-replace

Create domain pattern LLLLLLL/NNNNNN shortcut with PHP


I want to create a function that shortcut domain name pattern.

The only "law" of the function is that if there is a letter that repeats itself more than 5 times in a row such as LLLLLLL or NNNNNN or even mixed letter LLLLLLLNNNNNN we will get a shortcut in all cases ie 6 times of L sequence will change to L6 and so on in other cases.

Now I want to shorten the domin for example incase the string is 5 letters or numbers in sequence together, I want to create a shortcut.

  • For example:
    1. LLLLLLLL -> L8
    2. NNLLLLLLLN -> NNL7N
    3. LLLLLLLNNNNNN -> L6N6.

I thought at the first to use "str_replace" function but, the problem is there are infinite examples of shortening.


Solution

  • You could do a simple preg_replace that will utilize a pretty simple pattern to check the sequence. There is also a very similar question here - Encode/compress sequence of repeating integers

    function parseString( $string ) {
        return preg_replace('/(.)\1*/e', 'strlen($0) . $1', $string);
    }
    

    Then call it like so (passing in the string):

    echo parseString('NNLLLLLLLNNNLNLNNNN');