【问题标题】:phpbb BBCode to HTML (regex or otherwise)phpbb BBCode 到 HTML(正则表达式或其他)
【发布时间】:2014-12-13 13:05:01
【问题描述】:

我正在将内容从 phpBB 迁移到 WordPress。我已经成功地将 bbcode 翻译成 html。

BBCode 被注入到每个标签中的字母数字字符串复杂化。

一个普通的帖子会包含这样的文字......

[url=url] Click here [/url:583ow9wo]

[b:583ow9wo] BOLD [/b:583ow9wo]

[img:583ow9wo] jpg [/img:583ow9wo]

我对正则表达式缺乏经验,但我相信这可能是一条出路,因为我从以下帖子 https://stackoverflow.com/a/5505874/4356865 (使用正则表达式 [/?b:\d{5}] )中找到了一些帮助,但这里的正则表达式实例只会删除此示例中的数字字符。

任何帮助表示赞赏。

【问题讨论】:

  • 我自己从头开始编写正则表达式很垃圾,但txt2re.com 对开始找出要使用的正确表达式很有帮助。
  • 你不能使用网上流传的数万亿个 bbcode-to-html 转换器之一吗?

标签: html regex wordpress bbcode phpbb


【解决方案1】:

这样的东西适用于没有属性的标签:

\[(b|i|u)(:[a-z0-9]+)?\](.*?)\[\/\1(?:\2)?\]

\[               -- matches literal "[" 
  (b|i|u)        -- matches b, i, or u, captures as backreference 1
  (:[a-z0-9]+)?  -- matches colon and then alphanumeric string, captures as backreference 2
                 -- the question mark allows the :string not to be present.
\]               -- matches literal "]"
(.*?)            -- matches anything*, as few times as required to finish the match, creates backreference 3.
\[               -- matches literal "["
  \/             -- matches literal "/"
  \1             -- invokes backreference 1 to make sure the opening/closing tags match
  (?:\2)?        -- invokes backreference 2 to further make sure it's the same tag
\]               -- matches literal "]"

匹配像 url 这样的标签很容易

对于具有属性的标签,它们对属性执行不同的操作,因此将 URL 等标签与 IMG 等标签分开处理可能更容易。

\[(url)(?:\s*=\s*(.*?))?(:[a-z0-9]+)\](.*?)\[\/\1(?:\3)?\]

\[                    -- matches literal "["
  (url)               -- matches literal "url", in parentheses so we can invoke backreference 1 later, easier for you to modify
  (?:                 -- ?: signifies a non-capturing group, so it creates a group without creating a backreference, or altering the backreference count.
    \s*=\s*           -- matches literal "=", padded by any amount of whitespace on either side
    (.*?)             -- matches any character, as few times as possible, to complete the match, creates backreference 2
  )                   -- closes the noncapturing group
  (:[a-z0-9]+)        -- matches the alphanumeric string as backreference 3.
\]                    -- matches literal "]"
(.*?)                 -- matches any character as few times as possible to complete the match, backreference 4
\[                    -- matches literal "["
  \/                  -- matches literal "/"
  \1                  -- invokes backreference 1
  (?:\3)?             -- invokes backreference 3
\]                    -- matches literal "["

对于您的替换,标签的内容本身在反向引用中,因此您可以对 b/i/u 标签执行类似的操作。

<\1>\3</\1>

对于url标签,是这样的

<A href="\2">\4</A>

我说点/句点匹配多个位置的任何字符。它匹配除换行符以外的任何字符。您可以像这样使用"dotall" 修饰符s 来打开正则表达式中的换行修饰符

/(.*)<foo>/s

【讨论】:

    猜你喜欢
    • 2013-07-04
    • 1970-01-01
    • 1970-01-01
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    • 2012-06-22
    • 1970-01-01
    • 2012-05-21
    相关资源
    最近更新 更多