【问题标题】:Replace all text except links替换除链接以外的所有文本
【发布时间】:2011-01-15 09:33:06
【问题描述】:

我有很多html文档,我需要将所有文档中的文本“foo”替换为“bar”,链接除外

例如

foo<a href="foo.com">foo</a>

应该换成

bar<a href="foo.com">bar</a>

链接中的 url (foo.com) 应该保持不变。

图片链接和 javascripts 或样式表链接的情况相同,只需要替换文本,url 应该不变。

对一个好的正则表达式或其他东西有什么想法吗? :)

我也可以使用 Ruby :)

【问题讨论】:

    标签: html ruby regex string


    【解决方案1】:

    我建议使用hpricot,它只允许您对元素的inner_html 执行操作。你需要的不仅仅是一个正则表达式来获得你想要的东西。

    【讨论】:

      【解决方案2】:

      正则表达式无法解析 HTML。使用适合工作的工具,例如 XSLT:

      <?xml version="1.0"?>
      
      <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:template match="node()|@*">
          <xsl:copy>
            <xsl:apply-templates select="@*"/>
            <xsl:apply-templates/>
          </xsl:copy>
        </xsl:template>
      
        <xsl:template match="//text()[name(..) != 'script']">
          <xsl:call-template name="replace-foo" />
        </xsl:template>
      
        <xsl:template name="replace-foo">
          <xsl:param name="text" select="." />
          <xsl:choose>
            <xsl:when test="contains($text, 'foo')">
              <xsl:value-of select="substring-before($text, 'foo')"/>
              <xsl:text>bar</xsl:text>
              <xsl:call-template name="replace-foo">
                <xsl:with-param name="text" select="substring-after($text, 'foo')"/>
              </xsl:call-template>
            </xsl:when>
            <xsl:otherwise>
              <xsl:value-of select="$text"/>
            </xsl:otherwise>
          </xsl:choose>
        </xsl:template>
      </xsl:stylesheet>
      

      使用以下输入

      <html>
      <head><title>Yo!</title></head>
      <body>
      <!-- foo -->
      foo<a href="foo.com">foo</a>
      <script>foo</script>
      </body>
      </html>
      

      你会得到

      $ xsltproc replace-foo.xsl input.html
      <html>
      <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>Yo!</title>
      </head>
      <body>
      <!-- foo -->
      bar<a href="foo.com">bar</a>
      <script>foo</script>
      </body>
      </html>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-21
        相关资源
        最近更新 更多