我希望将以下字符串从源转换为目标,然后再从目标转换到源。
$strSource = '<g id="5">fist test string</g> <d id="20">some random string</d>';
$strTarget = '{1}fist test string{2}some random string{3}';
我找到的解决方案是使用数组和preg_replace。
我只是想知道是否有有效的解决方案可以使用 xslt 进行此转换。允许使用其他数据。数据可以包含任何帮助信息。
更新:
这是我使用preg_match_all的目标>源的解决方案,只是为了更好地理解:
preg_match_all('/(<.*>)(?!'s*<)/U', $strSource, $arrResult);
echo preg_replace('/{('d+)}/e', 'arrResult[1]["$1" - 1]', $strTarget);
XSLT 2.0 支持正则表达式,另一边是 XSLT 1.0 解决方案:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:strip-space elements="*"/>
<xsl:param name="pSuffix" select="'FR'"/>
<xsl:template match="/*">
<xsl:apply-templates/>
<xsl:value-of select=
"concat('{',g[last()]/@id +1, '}')"/>
</xsl:template>
<xsl:template match="g">
<xsl:value-of select=
"concat('{',@id, '}',
substring-before(., '_'), '_', $pSuffix
)"/>
</xsl:template>
</xsl:stylesheet>
当应用于此 XML 文档(您的"字符串",包装到单个顶部元素中以使其成为格式正确的 XML 文档)时:
<t>
<g id="1">TEST_EN</g> <g id="2">TEST_EN</g>
</t>
产生所需的正确结果:
{1}TEST_FR{2}TEST_FR{3}
反向变换:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes"/>
<xsl:strip-space elements="*"/>
<xsl:param name="pSuffix" select="'EN'"/>
<xsl:template match="text()" name="makeXml">
<xsl:param name="pText" select="."/>
<xsl:param name="pId" select="1"/>
<xsl:if test=
"contains($pText, '{') and contains($pText, '}')">
<xsl:variable name="vPiece" select=
"substring-before(substring-after($pText, '}'), '{')"/>
<g id="{$pId}"><xsl:value-of select=
"concat(substring-before($vPiece, '_'), '_', $pSuffix)"/></g>
<xsl:call-template name="makeXml">
<xsl:with-param name="pId" select="$pId +1"/>
<xsl:with-param name="pText" select=
"substring-after(substring-after($pText, '}'), '{')"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
当此转换应用于第一个转换的结果时(再次包装在单个顶部元素中以使其成为格式正确的 XML 文档):
<t>{1}TEST_FR{2}TEST_FR{3}</t>
产生所需的正确结果:
<g id="1">TEST_EN</g><g id="2">TEST_EN</g>