我有很多的html文件,我需要替換文本「富」到「欄」裏的所有文件,除了在鏈接更換除鏈接的所有文字
例如
foo<a href="foo.com">foo</a>
應raplaced到
bar<a href="foo.com">bar</a>
鏈接(foo.com)中的網址應該保持不變。
在圖像鏈接和鏈接到JavaScript或樣式表的相同情況下,只有文本應該被替換,網址應該保持不變。
任何想法一個很好的正則表達式或東西? :)
我可以使用Ruby太:)
我有很多的html文件,我需要替換文本「富」到「欄」裏的所有文件,除了在鏈接更換除鏈接的所有文字
例如
foo<a href="foo.com">foo</a>
應raplaced到
bar<a href="foo.com">bar</a>
鏈接(foo.com)中的網址應該保持不變。
在圖像鏈接和鏈接到JavaScript或樣式表的相同情況下,只有文本應該被替換,網址應該保持不變。
任何想法一個很好的正則表達式或東西? :)
我可以使用Ruby太:)
我推薦使用hpricot,這將讓你執行僅元素的inner_html
行動。你需要的不僅僅是一個正則表達式來獲得你想要的東西。
正則表達式無法解析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>
好主意,它的作品!謝謝 :) – astropanic 2010-02-10 20:00:51