Quantcast
Channel: TechKnack
Viewing all articles
Browse latest Browse all 10

PHP Templating: Variable Date

$
0
0

In building a template system, you may want some way to inject date info using a timestamp (perhaps generated through mktime() ) and date(). But you don’t want the format to be dependent on the template parser, but rather specified through the variable in the template itself.

$template = preg_replace(
    "#\%date(\:\s*(.*?))?\%#ei",
    "date(('\\2'!=\"\"?'\\2':\$date_format), \$timestamp)",
    $template
);

This falls on the “advanced” side of intermediate, I would think, so here’s an explanation:

This is a standard preg_replace($pattern, $replacement, $source_string). What we want to do is replace the variable %date% in $template with a date string generated from $timestamp. But %date% is too limiting; within the template, we’d like to write something like %date: F j, Y% to get a date like “March 12, 2009,” or any other format.

The regular expression is like so: #\%date(\:\s*(.*?))?\%#ei. The “hashes” (#) here act as delimiters for the regex; the e and i after the second hash turn on “eval’d replacement” and “case-insensitivty”, respectively (learn more about PCRE regex modifiers at php.net). So the regex to deal with is \%date(\:\s*(.*?))?\%. The \% are the markers for our template variables; date is the name of the variable to look for. (\:\s*(.*?))? matches zero or one instances of our “variable modifier”: a colon, followed by any amount of whitespace (including none), followed by any number of any characters (where the extra ? makes the .* “non-greedy”; it’ll stop “eating” characters when it reaches the next percent sign). For preg_replace, this will place our date() format in “\\2″ if it is present; if it is not present, “\\2″ will not be set.

The replacement is as follows: “date((’\\2′!=\”\”?’\\2′:\$date_format), \$timestamp)”. preg_replace will insert the matched date format from the regex into every occurrence of “\\2″ in the replacement string, and then run eval() on the resulting string to get the replacement value (all thanks to the e modifier in the regex). Assuming our regex matched “F j, Y” as the match, we’ll get “date((’F j, Y’!=\”\”?’F j, Y’:\$date_format), \$timestamp)”. The (’F j, Y’!=\”\”?’F j, Y’:\$date_format) part chooses the date format; if the match is not set (ie, an empty string), use whatever is in the variable $date_format; else, if the date format was matched, use it. This allows us to use %date% in the template, to default to a server-side specified format.

And there it is. You can now put “%date: F j, Y%” in your template, and it will be expanded to “March 12, 2009″ (depending on the actual date, of course :) ). That is, if your templating system works in the first place…


Viewing all articles
Browse latest Browse all 10

Trending Articles