2010-02-10 35 views
2

我有很多的html文件,我需要替换文本“富”到“栏”里的所有文件,除了在链接更换除链接的所有文字

例如

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

应raplaced到

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

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

在图像链接和链接到JavaScript或样式表的相同情况下,只有文本应该被替换,网址应该保持不变。

任何想法一个很好的正则表达式或东西? :)

我可以使用Ruby太:)

回答

1

我推荐使用hpricot,这将让你执行仅元素的inner_html行动。你需要的不仅仅是一个正则表达式来获得你想要的东西。

+0

好主意,它的作品!谢谢 :) – astropanic 2010-02-10 20:00:51

1

正则表达式无法解析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> 
相关问题