Using preg_replace with Edge Side Includes (ESI)

(Tom Stringer) #1

I’m trying to use the ^preg_replace keyword modifier in an esi:when test statement but I’m having difficulty getting it to work. The ^preg_match modifier seems to work fine, but it’s not quite what I need in this instance.

In this case, I’m interrogating the contents of a cookie to return segmented content.

The following works fine (FYI - %globals_cookie_example^preg_match:12345% returns 1):

<esi:when test="(%globals_cookie_example^preg_match:12345% == 1)">
  <h2>Some content</h2>

But this next statement doesn’t (FYI - %globals_cookie_example^preg_replace:12345% returns ‘desiredValue’):

<esi:when test="(%globals_cookie_example^preg_replace:12345% == 'desiredValue')">`
  <h2>Some content</h2>

Any ideas why that might be the case? Is preg_replace performed on the server where preg_match is not?

(Tyson Adams) #2

Hi Tom,

%preg_match% is a boolean check (does the cookie match this) whereas %preg_replace% will just replace the match with whatever you supply (replace the matching cookie value), so it depends on what you have set in the Regular Expression asset (im assuming that’s what your assetid is there?)

So if you are wanting to show content based on cookie contents, then preg_match should be what you are after, coupled with whatever regex you have set up in your Regular Expression asset.

(Tom Stringer) #3

Hi Tyson

Ah! I needed to stringify the second statement because it’s no longer returning a boolean.

Should be:

<esi:when test="('%globals_cookie_example^preg_replace:12345%' == 'desiredValue')">

That got it.

(David Schoen) #4

@tomstringer The %globals_cookie_example^preg_replace:12345% keyword is evaluating at Matrix and compiling to a literal string before <esi:when test="('some literal string here' == 'desiredValue')"> is sent to whatever ESI processor is involved in your stack, so this isn’t going to make sense as you’re going to end up storing the cookie value from whatever the first request to get cached is and then continuing to check that at the ESI processor while the cache object is valid.

Assuming you’re using Squiz Edge, the standard cookie checks are supported as per . Squiz Edge also supports regex comparisons like:

  <esi:when test="$(HTTP_COOKIE{example}) =~ '/desiredValue/i'">

Alternatively if it makes sense to check the cookie back at Matrix (e.g because the current object is never cacheable) you could use Matrix conditional keywords to selectively emit either regular content or a normal <esi:include.

(David Schoen) #5

A little more context:

(Tom Stringer) #6

Excellent point. I’ll have a closer look at the Squiz Edge regex comparisons for this.

And thanks for those docs!