Conditional conundrums

16 July 2014 4 comments

As I mentioned earlier, ExpressionEngine 2.9 comes with changes in its conditional parser. While these changes are a Good Deal for EE, it does come with a couple of gotchas. Here is one that directly affects one of my add-ons.

IN conditionals no longer work

The IN conditionals that Low Search made available are no longer valid conditionals and will throw an error when used in EE 2.9. Thankfully, we can use an alternative to check whether a value exists in a pipe-separated list of items: with the Matches Operator. This will allow us to use regular expressions in conditionals. Let’s see how:

EE <= 2.8.1

{if 'foo' IN ('foo|bar|baz')} ... {/if}
{if 2 IN (1|2|3)} ... {/if}
{if 'lorem' NOT IN ('lorem|ipsum|dolor|sit amet')} ... {/if}

And with Low Search, you would have used something like this:

{if category_id IN ({low_search_category})} ... {/if}

…where {low_search_category} would contain a pipe-separated list of category IDs.

EE >= 2.9.0

{if 'foo|bar|baz' ~ '/(^|\|)foo($|\|)/'} ... {/if}
{if '1|2|3' ~ '/(^|\|)2($|\|)/'} ... {/if}
{if !('lorem|ipsum|dolor|sit amet' ~ '/(^|\|)lorem($|\|)/')} ... {/if}

And with Low Search, you would have to use something like this:

{if low_search_category ~ '/(^|\|)'.category_id.'($|\|)/'} ... {/if}

Note that we’re also using EE’s new string concatenation operator to compose the regular expression.

Regular expressions? Halp!

Don’t fear the Regex. It looks weird, but it’s a powerful tool to have. Play around with the syntax with this great tool to get familiar with it. Once you feel comfortable with it, you’ll also understand the potential pitfalls, for example:

Variables that are part of the regex pattern aren’t escaped by ExpressionEngine. For the most part, this isn’t a problem, but it can lead to unexpected results or errors. Make sure the values don’t interfere with the pattern delimiters (the first and last character of the pattern: a forward slash in these examples) or contain regex characters. Remember that, and you’re golden.


  1. Mark Croxton 16 July 2014 at 13:49

    You can escape a string in a regular expression by prepending with \Q and appending \E. For example: {if this ~ '/\Q'.that.'\E/'} ... {/if}

  2. Lodewijk Schutte 16 July 2014 at 13:50

    Top tip right there, Mark!

  3. Mark Biesheuvel 16 July 2014 at 16:35

    Wouldn’t it be possible to use something like

    {if '2' ~ '/^(1|2|3)$/'} ... {/if}


    {if category_id ~ '/^('.low_search_category .')$/'} ... {/if}

    This will work because the pipe character is kind of like an IN in regular expressions.

  4. Lodewijk Schutte 16 July 2014 at 16:41

    You could, but… Security. If, in Low Search, you change the value of the low_search_category variable by changing the query, you could end up breaking the site, because of a faulty regular expression. That’s why I flipped the values like that.

Commenting is not available in this channel entry.