Capture Group, (*SKIP)(*F)
or Split
To match this, we have several options.
Option 1: With capture groups
This is a longer way to do it, but it will work in all engines.
\[!--[^-]*--\]|((?:(?!\[!--[^-]*--\]).)+)
The strings you want are in Group 1. In the Regex Demo, look at the captures in the right panel.
Option 2: (*SKIP)(*F)
This will only work in Perl and PCRE (and therefore PHP). It matches the strings directly.
\[!--[^-]*--\](*SKIP)(*F)|(?:(?!\[!--[^-]*--\]).)+
In the Regex Demo, see the matched strings.
Option 3: Split
Match All and Split are Two Sides of the Same Coin, so we can use preg_split
instead of preg_match_all
. By splitting the string, we remove the pieces we want to exclude.
$element_regex = '~\[!--[^-]*--\]~';
$theText = preg_split($element_regex, $yourstring);
Explanation
This problem is a classic case of the technique explained in this question to "regex-match a pattern, excluding..."
Option 1. In Option 1, The left side of the alternation |
matches complete [!--$element--]
. We will ignore these matches. The right side matches and captures other text, and we know it is the right ones because it was not matched by the expression on the left.
Option 2. In Option 2, the left side of the alternation |
matches complete [!--$element--]
then deliberately fails, after which the engine skips to the next position in the string. The right side matches the this
word you want, and we know they are the right ones because they were not matched by the expression on the left.
Reference