Search code examples
phpscanfuuidtext-parsing

Parse a formatted string -- isolate quoted substring and curly braced UUID


I am trying to parse a list of operating system instances with their unique identifiers. I am looking for a solution to parse a text string, and pass the values into two variables. The string to be parsed is as followed:

"Ubuntu 9.10" {40f2324d-a6b2-44e4-90c3-0c5fa82c987d}

Solution

  • I've been looking for an excuse to read the docs for sscanf():

    sscanf($s, '"%[^"]" {%[^}]}', $os, $ident);
    echo $os, "<br>", $ident;
    

    Followup: For interest's sake, out of the three answers currently on this question:

    sscanf: 0.92999792098999 seconds
    preg_match: 4.73761510849 seconds
    str_replace x2 + preg_split: 3.7644839286804 seconds
    

    Benchmark here. Funny that two str_replace() and a preg_split() are faster than the preg_match().