[英]Regular expression - replace multiple html tags with one
is there a regular expression or any way to replace the following: 是否有正则表达式或任何方式替换以下内容:
some content...<span style='color:red'>t</span><span style='color:red'>e</span><span style='color:red'>s</span><span style='color:red'>t</span> some content
with this? 有了这个?
some content... <span style='color:red'>test</span> some content
If the HTML tags are all the same, you can just use String.replace . 如果HTML标记都相同,则可以只使用String.replace 。
var oldStr = "<span style='color:red'>t</span><span style='color:red'>e</span><span style='color:red'>s</span><span style='color:red'>t</span>";
var newStr = oldStr.replace("</span><span style='color:red'>", "");
There are opinions that regex should not be used to process HTML. 有意见认为正则表达式不应用于处理HTML。
If you agree, you can use the following XSLT transformation. 如果您同意,则可以使用以下XSLT转换。
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="html" doctype-public="XSLT-compat"
encoding="UTF-8" indent="yes" />
<xsl:strip-space elements="*"/>
<xsl:template match="span">
<xsl:copy>
<!-- Copy attributes and text from the current span -->
<xsl:apply-templates select="@*|node()"/>
<xsl:variable name="nextSpans" select="following-sibling::span"/>
<!-- Copy text from following spans -->
<xsl:for-each select="following-sibling::node()">
<xsl:variable name="ind" select="position()"/>
<xsl:if test="generate-id()=generate-id($nextSpans[$ind])">
<xsl:value-of select="."/>
</xsl:if>
</xsl:for-each>
</xsl:copy>
</xsl:template>
<!-- Switch off processing of "following" spans -->
<xsl:template match="span[preceding-sibling::node()[1]/name()='span']"/>
<xsl:template match="@*|node()">
<xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
</xsl:template>
</xsl:stylesheet>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.