问题
I'm trying to remove BBCode from a given string (just using gsub
with some regex).
Here's an example string:
The [b]quick[/b] brown [url=http://example.com]fox[/url] jumps over the lazy dog [img=http://example.com/lazy_dog.png]
And what I need that to output is:
The quick brown fox jumps over the lazy dog
So what's a way to do that? I've found various examples of doing this, but none have worked for my use case.
One that I've tried: /\[(\w+)[^w]*?](.*?)\[\/\1]/
But that wouldn't catch the ending [img]
tag.
回答1:
The purpose of this post is to show the disparity in how the BBCode is interpreted, which one should take into consideration when stripping the BBCode tags while preserving the content
This will only remove BB code tags as defined by this page.
It may remove more than what is considered valid BB code tag, though. For example, [b ]Bold[/b]
is not bolded by this BBCode tester, so by right, those tags should be left alone. But [\b]
will be removed by the regex below. It will also remove clearly non-BBCode such as [\b=something]
Another example is [url=http://example.com/ ][/url]
(note the space). This might be OK or not OK depending on the BBCode parser. The regex below ignores the opening tag, but removes the closing tag.
/\[\/?(?:b|u|i|s|size|color|center|quote|url|img|ul|ol|list|li|\*|code|table|tr|th|td|youtube|gvideo)(?:=[^\]\s]+)?\]/
The [code]
tag is also not treated correctly by the regex as seen in this demo. The replacement should leave [code]
in between code
tag alone.
This BBCode tester allows [b][b][b]Text[/b][/b][/b]
to be parsed into Text
bolded, but the other one interpret it as [b][b]Text[/b][/b]
with the part [b][b]Text
bolded and the rest not bolded. If you allow nested tags, then regex is not a good choice.
来源:https://stackoverflow.com/questions/14695333/ruby-regex-for-stripping-bbcode