This will be a short tutorial how to build twig extension that uses regular expressions. Let’s say you have a html document in your variable and you want to extract image or paragraph from that variable. If you were to look at twig’s filters and functions you’d soon notice there’s nothing that can help you accomplish that task Twig Documentation

Luckily you can easily extend twig’s initial set of functions and filters and it’s fairly simple.

First create folder named Twig in your bundle and then create RegexExtension.php and copy paste the following.

Don’t forget to change namespace to match that of your application.

Check that your file structure matches:

AcmeBundle – Resources – config services.xml

Copy paste the following to enable your twig extension.

Also don’t forget to make your dependency injection folder and required files.

Your file structure should match this one:

AcmeBundle – DependencyInjection AcmeExtension.php Configuration.php

Your configuration file should look like this:

And your extension file like this:

Now to use your newly created filter within twig template you just write:

{{ varWithHtml|regex|raw }}

That will extract one image and one paragraph.

{{ varWithHtml|regexPhoto|raw }}

This will extract only one image. Raw filter is used to show the image and paragraph.

If you would like to create twig functions you just change getFilters method to getFunctions. This is only small part of what can twig do for you and if you’re using PHP and looking for a templating engine I would definitely recommend you to start using twig.

Before you start writing your own extensions first check twigs filters and functions because oftentimes there is some hidden feature you might have missed.