15

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) %}
6
  • 5
    This question is a better fit the on StackOverflow site. Commented Jun 16, 2014 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. Commented Jun 16, 2014 at 13:47
  • 1
    Yes, your edit makes the question relevant to Craft. Commented Jun 16, 2014 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. Commented Jun 16, 2014 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
    Commented Jun 16, 2014 at 17:55

3 Answers 3

21

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:

1
5

This works for me just fine:

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

Answers for 2023 using Craft CMS 4

For simple find and replace: you can just use the replace filter, it accepts RegEx now.

For more complicated lookups: If you're looking to just add Craft CMS filters in general or use PHP filters, like preg_match_all() you can install the Twig Toolbox plugin, create the file config/twig-toolbox.php with the following code to enable the filter or add more as needed:

<?php return [
    'filters' => [
        'preg_match_all' => function(string $subject, string $pattern): array {
            preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER);
            return $matches;
        },
    ],
    'functions' => [],
    'globals' => [],
    'tests' => [],
];

Please note, the above filter is a basic version of the actual preg_match_all, see the full documentation and adapt as you see fit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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