TransWikia.com

PHP preg_replace pattern inside curly brackets, but ignoring "flags" inside square brackets

Stack Overflow Asked by Q Studio on November 22, 2021

Given the following string:

Tags are inside {{ curvy }} brackets, but may also include {{ [f] flags }} in square brackets

I need to return just the "variables" – in this case "curvy" and "flags", while ignoring the flags.

I have 2 seperate regexs to achieve this, but I need the original string to remain unchanged, so I need to find a way to merge into a single regex which finds the variables, but ignores the flags.

Here are the two regexes I have now:

Grabs variables in {{ var }} –> ~{{s+(.*?)s+}}~

Grabs flags [f] OR [fdc] –> ~/[.*?]/~

The first regex works, but returns the variables with the flag.

One Answer

You may use

{{(?:s*[[^][{}]*])?s*(.*?)s*}}

See the regex demo

Details

  • {{ - {{ substring
  • (?:s*[[^][{}]*])? - an optional non-captuiring group matching 0+ whitespaces, [, any 0 or more chars other than [, ], { and } and then ]
  • s* - 0+ whitespaces
  • (.*?) - Group 1 capturing any zero or more chars other than line break chars as few as possible
  • s* - 0+ whitespaces
  • }} - }} substring

Answered by Wiktor Stribiżew on November 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP