S
S
serjioms2015-03-17 13:44:16
PHP
serjioms, 2015-03-17 13:44:16

How to generate unique 36 character id using php/js?

How to generate using php id like: e7436adb-18e9-4295-939f-2325b64225bb?
Or using js.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Melnikov, 2015-03-17
@mlnkv

it's better then

function generate(str) {
  return str.replace(/[xy]/g, function(c) {
    var r = Math.random() * 16 | 0;
    return (c == 'x' ? r : (r & 0x3 | 0x8 )).toString(16);
  });
}

generate('xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx');
// "03bcf8e8-92de-4afd-9575-955d6ea94f70"

S
serjioms, 2015-03-17
@serjioms

js code dug up like this:

generateUUID = function () {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace( /[xy]/g, function ( c ) {
            var r = Math.random() * 16 | 0;
            return ( c == 'x' ? r : ( r & 0x3 | 0x8 ) ).toString( 16 );
        } );
    };

for PHP I wrote the following mask generator:
protected function generateUId()
    {
        $idMask = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

        $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
        $result = '';
        for ($i = 0; $i < strlen($idMask); $i++) {
            if ($idMask[$i] == 'x') {
                $result .= $characters[mt_rand(0, 34)];
            } else {
                $result .= "-";
            }
        }
        return $result;
    }

S
smanioso, 2015-03-17
@smanioso

PHP
https://gist.github.com/dahnielson/508447
https://github.com/ramsey/uuid
https://www.npmjs.com/package/uuid
https://www.npmjs.com/search ?q=uuid

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question