Reading querystring variables using SSI and regular expressions

In these days I worked on a project into which I have to rely on SSI (apache’s Server Side Includes) in order to read and use url parameters to dynamically include certain html files with “include virtual” directive. Unfortunately the documentations available online is not exhaustive, and I had to figure out some things by myself.
Anyway, according to the docs, there are several global variables we can use in SSI, two of these are: DOCUMENT_URI and QUERY_STRING, which are the two we can use to handle the page url. The first returns the (%-decoded) URL path of the document, the second all the string starting with “?”.
So, how we can extract our desired variables from these strings, since SSI doesn’t offer method such “substring”, “split”, “indexOf” and similar? The answer is: by using Regular Expression in a tricky and ingenious way!
SSI offers a basic way to implementing decision flow (if, else, elif), the if command has an attribute expr which represents a declaration to be valuated, in this attribute is also possible to use a regex to test a given pattern. By knowing this, is possible to declare an SSI variable which represents the desired querystring parameter in the following way:

<!--#if expr="$QUERY_STRING = /year=([0-9]{4})/" -->
	<!--ssi-comment: year found -->
	<!--#set var="year" value="$1" -->
<!--#else -->
	<!--ssi-comment: year NOT found -->
	<!--#set var="year" value="$DATE_LOCAL" --> 
<!--#endif -->

In the code above I’m looking to a querystring parameter called year which must be a 4 ({4}) digit number ([0-9]).
If the pattern tested returns true, the matched value (returned by the regex) will be assigned to the SSI variable year, otherwise the current server date year ($DATE_LOCAL) will be assigned.

1. “ssi-comment:” is not a special syntax, but just a comment style I decided to adopt to be readable and understandable.
2. To get only the year from $DATE_LOCAL variable, you must config the format using “#config timefmt=”%Y””