Parsing BBCode with xslt 2.0

2019-06-04 19:17发布

I need help finding a viable solution to convert bbcode to html, this is where ive come so far, but fails when bbcodes get wrapped.

Src:

 [quote id="ohoh81"]asdasda
     [quote id="ohoh80"]adsad
         [quote id="ohoh79"]asdad[/quote]
     [/quote]
 [/quote]

Code:

<xsl:variable name="rules">
    <code check="&#xD;" >&lt;br/&gt;</code>
    <code check="\&#91;(quote)(.*)\&#93;" >&lt;span class=&#34;quote&#34;&gt;</code>
</xsl:variable>

<xsl:template match="text()" mode="BBCODE">
  <xsl:call-template name="REPLACE_EM_ALL">
    <xsl:with-param name="text" select="." />
    <xsl:with-param name="pos" select="number(1)" />
  </xsl:call-template>
</xsl:template>

<xsl:template name="REPLACE_EM_ALL">
  <xsl:param name="text" />
  <xsl:param name="pos" />
  <xsl:variable name="newText" select="replace($text, ($rules/code[$pos]/@check), ($rules/code[$pos]))" />
  <xsl:choose>
    <xsl:when test="$rules/code[$pos +1]">
      <xsl:call-template name="REPLACE_EM_ALL">
        <xsl:with-param name="text" select="$newText" />
        <xsl:with-param name="pos" select="$pos+1" />
      </xsl:call-template>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of disable-output-escaping="yes" select="$newText" />
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

2条回答
唯我独甜
2楼-- · 2019-06-04 19:59

This is probably a bad idea because XSLT is designed to handle well-formed XML, not arbitrary text. I'd suggest you preprocess the BBCode first to replace the left and right brackets with < and >, do whatever else you need to to make it well-formed XML, and then process it with XSL.

查看更多
乱世女痞
3楼-- · 2019-06-04 20:04

I think a more viable approach would be to repeatedly match and replace (via regex) pairs of BBcode tags, until you get no matches. E.g. for [quote] and [url]:

<xsl:function name="my:bbcode-to-xhtml" as="node()*">
  <xsl:param name="bbcode" as="xs:string"/> 
  <xsl:analyze-string select="$bbcode" regex="(\[quote\](.*)\[/quote\])|(\[url=(.*?)\](.*)\[/url\])" flags="s">
    <xsl:matching-substring>
      <xsl:choose>
        <xsl:when test="regex-group(1)"> <!-- [quote] -->
          <span class="quote">
            <xsl:value-of select="my:bbcode-to-xhtml(regex-group(2))"/>
          </span>
        </xsl:when>
        <xsl:when test="regex-group(3)"> <!-- [url] -->
          <a href="regex-group(4)">
            <xsl:value-of select="my:bbcode-to-xhtml(regex-group(5))"/>
          </a>
        </xsl:when>
      </xsl:choose>
    </xsl:matching-substring>
    <xsl:non-matching-substring>
      <xsl:value-of select="."/>
    </xsl:non-matching-substring>
  </xsl:analyze-string>
</xsl:function>
查看更多
登录 后发表回答