Search code examples
phpmustachemustache.php

PHP - validate mustache template


How do I validate a mustache template string in PHP? For example, if I pass

Hi {{#name}}{{name}}{{/name}}{{^name}}guest{{/name}}

and the validator should return valid, but if I pass

Hi {{#name}}{{name}}{{/name}}{{^name}}guest

it should return invalid.

Note I'd rather this to be done fully in PHP with no Mustache_Engine or any other 3rd party dependency.


Solution

  • It's not possible to correctly validate all valid mustache templates without building a mustache parser. There is no regular expression shortcut. You need an actual parser.

    If you're okay with some false negatives (and some false positives) you could build something to validate a subset of them. Or you can build a proper parser. But your best bet is to use mustache.php to parse it, as indicated in other answers.

    Why are you trying to do this without any dependencies?