2

I am working with template files that contain lines like these:

[field name="main_div" type='smallblock' required="yes"]
[field type='bigblock' color="red" name="inner_div"]
[field name="btn" type='button' caption='Submit']

mixed with HTML lines.

It's pseudocode for html code generation according to attribute values.

I have limited set of attributes, but don't control their order in string and presence of all of them. Sometimes "required" attribute is set, sometimes is missed, for example.

What is the easiest and convenient way to parse such strings, so I can work with attributes as associative array?

Regular expression, finite state machine, get substring from [ to ], explode by space and explode by equal sign?

Looking for advice or simple piece of code that can work with provided example.

1 Answer 1

3

Regular expressions. While you could write a parser for schemes like this, it's overkill and provides no resiliency against garbled tokens.

The trick is to use two regular expressions, one for finding the [field] tokens and a second to split out the attributes.

preg_replace_callback('/\[(\w+)(\s+\w+=\pP[^"\']*\pP)*\]/', "block", $);

function block($match) {

    $field = $match[1];

    preg_match_all('/(\w+)=\pP([^"\']+)\pP/', $match[2], $attr);
    $attr = array_combine($attr[1], $attr[2]);

    // ...
    return $html;
}
Sign up to request clarification or add additional context in comments.

4 Comments

I think, you forgot + here, yes: ([^"\']+) ?
@GalichevAnton: Yes, you can use + instead of * there. You could also change \pP back into the more explicit ["\'].
I was talking about preg_match_all expression. Can you modify answer, so I can accept it?
This type of solution is not safe. You should use finite state machine type parser to parse BB codes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.