Input (I doubled the string for effect):
$string = 'test{{this should not be selected and the curly brackets too}} but this one { or } should be selected. So I want to exclude all text between an opening and closing curly brackets. test{{this should not be selected and the curly brackets too}} but this one { or } should be selected. So I want to exclude all text between an opening and closing curly brackets.';
Method #1 preg_split()
:
var_export(preg_split('/{{[^}]*}}/', $string, 0, PREG_SPLIT_NO_EMPTY));
// Added the fourth param in case the input started/ended with a double curly substring.
Method #2 preg_match_all()
:
var_export(preg_match_all('/(?<=}{2}|^)(?!{{2}).*?(?={{2}|$)/s', $string, $out) ? $out[0] : []);
Output (either way):
array (
0 => 'test',
1 => ' but this one { or } should be selected. So I want to exclude all text between an opening and closing curly brackets. test',
2 => ' but this one { or } should be selected. So I want to exclude all text between an opening and closing curly brackets.',
)
preg_split()
treats the double curly wrapped substrings as "delimiters" and splits the full string on them.
The preg_match_all()
method pattern...
Pattern Demo This uses a positive lookbehind and a positive lookahead both of which hunt for double curlies or start/end of string. It uses a negative lookahead in the middle to avoid matching unwanted double-curly strings at the start of a new line. Finally the s
modifier at the end of the pattern will allow .
to match newline characters.