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) %}
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:
replace
filter now supports regular expressions...
Commented
Mar 23, 2015 at 18:48
This works for me just fine:
{# Removes all characters other than numbers and + #}
{{ profile.phone|replace('/[^0-9+]/', '') }}
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.
preg_get_all
. If you're trying to bold that text though, there's amarkdown
filter that can do that for you.