Удалите вложенные теги стиля bbcode и все, что находится внутри них

Мне нужна помощь с регулярным выражением, чтобы удалить некоторые вещи. Я не могу заставить его работать так, как я хочу.

Допустим, у меня есть этот текст:

for sure
Test [/quote] [this should not be removed] Dont remove me

Как я могу удалить все выше [this should not be removed]? Обратите внимание, что Test может быть что угодно.

Поэтому я хочу удалить что-нибудь внутри:

Я зашел так далеко:

preg_replace('#\
(.+)\
#Usi', '', $message);

Но это держит: Test [/quote]

0

Решение

Соответствие вложенного кода стиля 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]»
1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector