David Ludwig David Ludwig - 5 months ago 10x
PHP Question

PHP Regex: Matching Non-escaped Character Groups

Ok, so I've been trying to figure this out all day, playing around with various regular expressions in PHP. I have a string like this:

$str = "this is a(n) {item} made by {username}. Watch out for \\{escaped} items. This one is \\\\{notescaped}.";

I need to capture the non-escaped groups surrounded by curly braces. I plan on splitting the string at the groups (curly braces included) into an array using
so that I can later fill in the blanks with the needed info.

So the result of this should be:

// After preg_split
array (
[0] => "this is a(n) ",
[1] => " made by ",
[2] => ". Watch out for {escaped} items. This one is \\",
[3] => "."

// Captured delimiters from preg_split
[0] => "{item}",
[1] => "{username}",
[2] => "{notescaped}",

I know how to simply capture the group using the basic
but I need to make sure that it wasn't escaped. So something like
(3 backslashes) would still escape it. Also the characters inside of the curly braces can be any character, nothing specific, and nothing that needs to be checked for escaping. Any help on this is much appreciated!


Backslashes are a pain to work with, but this will find everything between "unescaped" braces:


As a string, it becomes this monster:

$re = "~(?<=^|[^\\\\])(?:[\\\\]{4})*[{]([^}]*)[}]~s";

Essentially, it ensures that there is an even number of backslashes before the bracket.