PHP function to generate v4 UUID

前端 未结 15 1365
眼角桃花
眼角桃花 2020-11-22 03:01

So I\'ve been doing some digging around and I\'ve been trying to piece together a function that generates a valid v4 UUID in PHP. This is the closest I\'ve been able to come

15条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 03:48

    Inspired by broofa's answer here.

    preg_replace_callback('/[xy]/', function ($matches)
    {
      return dechex('x' == $matches[0] ? mt_rand(0, 15) : (mt_rand(0, 15) & 0x3 | 0x8));
    }
    , 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx');
    

    Or if unable to use anonymous functions.

    preg_replace_callback('/[xy]/', create_function(
      '$matches',
      'return dechex("x" == $matches[0] ? mt_rand(0, 15) : (mt_rand(0, 15) & 0x3 | 0x8));'
    )
    , 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx');
    

提交回复
热议问题