Reputation: 577
I have a some template tags in a PHP file that I can't seem to match with a regular expression. Actually, what I'm using I've made work before but I can't make it work this time. All the template tags will look like this {$EXAMPLE}
, two squigglies surrounding a dollar sign followed by anything. Actually, the word example will always be uppercase and may contain underscores or dashes, but that part isn't really necessary. What I have already is this:
Template file:
{$HEADER}
{$MENU}
{$BODY}
{$FOOTER}
PHP file:
$template = file_get_contents(TEMPLATE);
preg_match_all('^{$.*}^U', $template, $matches);
var_dump($matches);
where var_dump
outputs an empty array.
Upvotes: 0
Views: 890
Reputation:
Since the curly braces and the dollar sign are meta-characters, you need to escape them with backslashes. Change your regular expression from ^{$.*}^U
to ^\\{\\$.*\\}^U
and your code will work perfectly.
Upvotes: 1
Reputation: 9351
Try this:
$template = file_get_contents(TEMPLATE);
preg_match_all('/^(\{\$.*\})^U/', $template, $matches);
var_dump($matches);
See live demo here: http://rubular.com/r/52kKX0dIdl
Upvotes: 1
Reputation: 89557
You can use this:
preg_match_all('~{\$[^}]+}~', $template, $matches); // negated character class + greedy quantifier
or
preg_match_all('~{\$[A-Z_-]+}~', $template, $matches); // follows your description
Upvotes: 1