Мне нужна помощь с регулярным выражением, чтобы удалить некоторые вещи. Я не могу заставить его работать так, как я хочу.
Допустим, у меня есть этот текст:
for sure
Test
[/quote]
[this should not be removed]
Dont remove me
Как я могу удалить все выше [this should not be removed]
? Обратите внимание, что Test
может быть что угодно.
Поэтому я хочу удалить что-нибудь внутри:
Я зашел так далеко:
preg_replace('#\(.+)\#Usi', '', $message);
Но это держит: Test [/quote]
Соответствие вложенного кода стиля bbcode довольно сложно — обычно с использованием синтаксического анализатора строк на основе нерегулярных выражений.
Кажется, вы используете PHP, он поддерживает регулярное выражение (?R)
синтаксис для «Рекурсия» используя это, мы можем поддерживать вложенный bbcode следующим образом.
Обратите внимание, что несоответствие открытия
пары не будут совпадать.
\[(quote)=[^]]+\](?>(?R)|.)*?\[/quote]
https://regex101.com/r/xF3oR6/1
$result = preg_replace('%\[(quote)=[^]]+\](?>(?R)|.)*?\[/quote]%si', '', $subject);
# \[(quote)=[^]]+\](?>(?R)|.)*?\[/quote]
#
# Options: Case insensitive; Exact spacing; Dot matches line breaks; ^$ don’t match at line breaks; Greedy quantifiers; Regex syntax only
#
# Match the character “[” literally «\[»
# Match the regex below and capture its match into backreference number 1 «(quote)»
# Match the character string “quote” literally (case insensitive) «quote»
# Match the character “=” literally «=»
# Match any character that is NOT a “]” «[^]]+»
# Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
# Match the character “]” literally «\]»
# Match the regular expression below; do not try further permutations of this group if the overall regex fails (atomic group) «(?>(?R)|.)*?»
# Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
# Match this alternative (attempting the next alternative only if this one fails) «(?R)»
# Match the entire regular expression (recursion; restore capturing groups upon exit; do not try further permutations of the recursion if the overall regex fails) «(?R)»
# Or match this alternative (the entire group fails if this one fails to match) «.»
# Match any single character «.»
# Match the character “[” literally «\[»
# Match the character string “/quote]” literally (case insensitive) «/quote]»
Других решений пока нет …