In PHP, I need to parse parameters in a string like:
{keyword name1=val1 name2='val2' name3="val3"}
And end up with an array like:
{
name1 => "val1",
name2 => "val2",
name3 => "val3"
}
Each value may or may not be quoted, and can be quoted using either single or double quotes. Also, values may contain spaces, punctuation characters, and even the opposite quote. for example, this could be a valid attribute:
name1="Isn't this OK?"
Ideally, it would also allow escaped quotes inside the value, but that would just be a bonus. I would love to have a function that operates just like the HTML browser parser does when it parses attributes on an HTML tag.
My first thought was to step through the string one character at a time, checking the character following the equal sign to see if it's a quote, then looking for the next matching quote. But that seems tedious and not exactly the most efficient way to parse the string.
The examples I've seen using regex are way over my head, unreadable, and way too complex for me to maintain.
I've also seen examples using DOMdocument, but they do not parse correctly when there is a space or comma inside the value.
I need to do this in PHP, not Javascript.
Is there a function (in PHP) that if I pass it just the attributes portion, it will return the array?