jansvabik jansvabik - 1 month ago 13
PHP Question

PHP incrementation of mixed content

please, can you help me with a PHP function that increments mixed content (0-9, a-Z, _, -) like this?

private function increment_mix($id) {
$chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-"

// I can not figure it out.
}

echo $this->increment_mix("5"); // 6
echo $this->increment_mix("Y"); // Z
echo $this->increment_mix("-"); // 00
echo $this->increment_mix("00"); // 01
echo $this->increment_mix("0z"); // 0A
echo $this->increment_mix("0-"); // 10
echo $this->increment_mix("mo"); // mp
echo $this->increment_mix("V--"); // W00

Answer

Here is a function that will do the job:

<?php
function increment_mix($id) {
    $chars = str_split("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-");
    $parts = str_split(strrev($id));

    $firstChar = "first";

    if(isset($parts[0])){
        $firstChar = $parts[0];
    }

    $parts[0] = "increace|".$firstChar;

    for($i = 0; $i < count($parts); $i++){
        if(strpos($parts[$i], "increace|") !== false){
            $charPart = str_replace("increace|", "", $parts[$i]);

            if($charPart == end($chars)){
                $parts[$i] = $chars[0];

                $nextChar = "first";

                if(isset($parts[$i+1])){
                    $nextChar = $parts[$i+1];
                }

                $parts[$i+1] = "increace|".$nextChar;
            }else{
                if($charPart == "first"){
                    $parts[$i] = $chars[0];
                }else{
                    $parts[$i] = $chars[array_search($charPart, $chars) + 1];
                }
            }
        }
    }

    return strrev(implode("", $parts));
}
?>

EDIT 2: If you want to use other characters in an other order you just need to edit the string in str_split() on line 3

EDIT: I'll add comments later when I have time