15

I've got a string that contains UUID v4

$uuid = 'http://domain.com/images/123/b85066fc-248f-4ea9-b13d-0858dbf4efc1_small.jpg';

How would i get the b85066fc-248f-4ea9-b13d-0858dbf4efc1 value from the above using preg_match()?
More info on UUID v4 can be be found here

hakre
  • 193,403
  • 52
  • 435
  • 836
Pav
  • 2,288
  • 4
  • 22
  • 25
  • not sure but try "^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$" – Rufinus Jun 03 '11 at 05:13
  • Again, Rufinus, this is wrong, see http://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_.28random.29 – Artefact2 Jun 03 '11 at 05:14

2 Answers2

21
$uuid = 'http://domain.com/images/123/b85066fc-248f-4ea9-b13d-0858dbf4efc1_small.jpg';
preg_match('!/images/\d+/([a-z0-9\-]*)_!i', $uuid, $m);

And

preg_match('/[a-f0-9]{8}\-[a-f0-9]{4}\-4[a-f0-9]{3}\-(8|9|a|b)[a-f0-9]{3‌​}\-[a-f0-9]{12}/', $uuid, $m);

works too. Taken from here, but I don't know if we can rely on that.

Alexandre Tranchant
  • 4,426
  • 4
  • 43
  • 70
Nemoden
  • 8,816
  • 6
  • 41
  • 65
  • No, this regex is waay too permissive. – Artefact2 Jun 03 '11 at 05:15
  • The question is how to get the `uuid` from link like that but not from anywhere, e.g. not from text. UUID Definition is [here](http://en.wikipedia.org/wiki/Uuid#Definition), so I guess my second solution which is, actually, stolen, would work right for this purpose. – Nemoden Jun 03 '11 at 05:20
  • 19
    A more strict regex would be `/[a-f0-9]{8}\-[a-f0-9]{4}\-4[a-f0-9]{3}\-(8|9|a|b)[a-f0-9]{3}\-[a-f0-9]{12}/` – Zoey Mertes Jul 13 '14 at 22:40
  • 3
    If the regex doesn't work though it looks correct: there are some invisible characters in the code examples which show up in the html source: ‌​ Working version without code highlighting: /[a-f0-9]{8}\-[a-f0-9]{4}\-4[a-f0-9]{3}\-(8|9|a|b)[a-f0-9]{3}\-[a-f0-9]{12}/ – stmllr May 16 '17 at 08:02
  • @ZachMertes The RFC also allows uppercase letters – Michael-O Mar 20 '20 at 21:09
9

You can try this simple pattern for uuids

preg_match('/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/',$uuid,$matches);
Toto
  • 89,455
  • 62
  • 89
  • 125
  • 1
    This is matching `________-____-____-____-____________` – Toto Jan 17 '20 at 15:51
  • 1
    Yeah, so don't use this. At least replace \w with [0-9a-f]: '/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/' – Kafoso Sep 30 '20 at 07:20