有谁知道在多个 html 文件中替换标签及其之间所有内容的最简单方法


Does anyone know the easiest way of replacing tags and everything in between them in multiple html files?

我有很多带有自定义样式表的html文件。我想创建一个他们都可以使用的通用样式表。所以我需要做的是更换

<样式类型>

.标题 {.... .body {..

在多个 HTML 文件中包含带有此标签的标签。

<链接媒体 href="style.css" type="text/css" rel="stylesheet" />

确定有人遇到了这个问题,我想知道完成此任务的最简单方法是什么? 是否有某种AppleScript或PHP脚本可以运行来执行此操作,或者是否有其他方法可以执行此操作?

我通常只在项目中使用TextMate的搜索或一些Ruby或shell脚本。我有一个这样的脚本保存为ggsub.rb,当我需要替换多个文件中的某些内容时,只需对其进行修改。

#!/usr/bin/env ruby -Ku
# paths = `find ~/Sites -name '*.html'`.chomp.split("'n")
paths = Dir["*.html"]
paths.each do |path|
  html = File.read(path)
  html.sub!(/<style.*?>.*?<'/style>/m,
  "<link rel='"stylesheet'" href='"style.css'">")
  puts html
  # File.open(path, "w") { |f| f.puts(html) }
end

请参阅今天早些时候发布的对这个问题的已接受答案。

如何使用preg_replace删除整个div

它非常接近您要做的事情。简而言之,使用 DOMDocument 类 - http://www.php.net/manual/en/class.domdocument.php