tmatthews
tmatthews

Reputation: 15

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}

Upvotes: 0

Views: 1095

Answers (3)

user7675
user7675

Reputation:

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().

Upvotes: 2

Michael Mrozek
Michael Mrozek

Reputation: 175415

You can use regular expressions to match the groups you need:

$str = '"Ubuntu 9.10" {40f2324d-a6b2-44e4-90c3-0c5fa82c987d}';
preg_match('/^"(.*)" {(.*)}$/', $str, $matches);

You can make the regular expression narrower based on the values (e.g. the second .* could be [0-9a-f-]+), but that's sufficient. $matches[1] will be "Ubuntu 9.10", and $matches[2] will be "40f2324d-a6b2-44e4-90c3-0c5fa82c987d"

Upvotes: 1

JYelton
JYelton

Reputation: 36512

This gets the two strings as first and second elements of a string array using str_replace and preg_split:

$s = "\"Ubuntu 9.10\" {40f2324d-a6b2-44e4-90c3-0c5fa82c987d}";
$s = str_replace("\" ", "|", $s); // substitute middle quotation mark and space for a delimiter
$s = str_replace("\"", "", $s); // remove quotation marks
$vars = preg_split('/\|/', $s); // split by delimiter
print_r($vars);

Upvotes: 0

Related Questions