Is it possible to perform a RegEx match on a string in Twig?

I'm looking for something like this:

{% set string = "This is **string**. **wer**  qewr **234**" %}
{% set match  = string.matches(/([*][*])(.*)([*][*])/g) %}
  • 5
    This question is a better fit the on StackOverflow site.
    – Anna_MediaGirl
    Jun 16 '14 at 12:55
  • 1
    I believe you'd have to extend twig for this. This looks like it has what you'd need, specifically the preg_get_all. If you're trying to bold that text though, there's a markdown filter that can do that for you. Jun 16 '14 at 13:47
  • 1
    Yes, your edit makes the question relevant to Craft.
    – Anna_MediaGirl
    Jun 16 '14 at 14:42
  • 1
    Here's a preg_replace implementation in a Craft plugin: github.com/low/low_regex. This should give you a framework to build what you need. Nice if the 'on hold' comes off your original question, and good fortune. Jun 16 '14 at 17:43
  • 2
    To open the question we need one more vote to reopen it. It's beside the edit and flag link.
    – Victor In
    Jun 16 '14 at 17:55

Currently Twig uses regular expressions only with Comparisons:

{% if string matches '{^[\d\.]+$}' %}
    Do Stuff
{% endif %}

Craft itself currently doesn't have any custom Twig filters or functions either.

But there are third-party plugins which might help you:


This works for me just fine:

{# Removes all characters other than numbers and + #}
{{ profile.phone|replace('/[^0-9+]/', '') }}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.