DEV Community

Jack H. Peterson
Jack H. Peterson

Posted on

1

Using matches & regex in Twig!

Problem

You may be having trouble with using regex and links in twig/php!

Typical Solution

Generally, You'd want to escape a slash!
Example:
/path/to/resouces/
would look something like this in js:
/\/path\/to\/resources\//
/ === delimiter
\/ === escaped slash

This doesn't play nicely with twig!
I figure twig is trying to be smart and escape things for you.
but I'm not really sure whats going on.

Real Solution

(Thankfully, php provides a way to work around this issue.)[https://www.php.net/manual/en/regexp.reference.delimiters.php]

Alternate delimiters:
/foo/ | #foo# | +foo+ | %foo% | <foo> | (foo) | {foo} | [foo]
All of the above delimiters are valid!

Applied Solution

This means, if we take our URL:
/path/to/resouces/
We just need to wrap it with a delimiter which isn't used in the string.
Example:
{/path/to/resouces/}
That's it! The regex should work how you'd like it to.

Wrap Up

Regex is weird.
Twigs undocumented behavior is weird.
together they're an afternoon of frustration.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (1)

Collapse
 
ianbromwich profile image
Ian B

Cheers, this pointed me in the right direction! the lack of official documentation is crazy 🤯

I had to format this regex like this to get working in twig

/\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d([+-][0-2]\\d:[0-5]\\d|Z)$/
Enter fullscreen mode Exit fullscreen mode

🤢

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay