首页 > 解决方案 > 上传前为数百个 html 文件批量替换 div 的内容

问题描述

我有一个包含数百个静态 html 文件的网站。我需要用 disqus 评论替换 facebook 评论。

下面是保存评论的 div 现在的样子:

<div id="commentsBar">
<div class="fb-comments" data-href="https://theinternet.io/pages/Sure-why-not.html" data-numposts="6" data-colorscheme="light"></div>
</div>

我需要用另一个形式的 div 替换“fb-comments”类的每个 div:

<div id="disqus_thread"></div>
<script>

/**
*  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION     BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
*  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT:     https://disqus.com/admin/universalcode/#configuration-variables*/
/*
var disqus_config = function () {
this.page.url = PAGE_URL;  // Replace PAGE_URL with your page's canonical URL variable
this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
};
*/
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = 'https://EXAMPLE.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>

PAGE_URL 是“fb-comments”div 中列出的 url。

有人知道如何做到这一点吗?

我看过的大多数文本编辑器只允许您查找和替换,这不起作用,因为每个 html 页面的 fb-comments div 中的 url 都不同。

标签: htmlregexbatch-processing

解决方案


不赞成使用正则表达式来做到这一点。

如果没有选项,则此表达式可能会使用preg_replacePHP 中的 a 来执行此操作,例如:

$re = '/<div class="fb-comments".*?<\/div>/s';
$str = '<div id="commentsBar">
<div class="fb-comments" data-href="https://theinternet.io/pages/Sure-why-not.html" data-numposts="6" data-colorscheme="light"></div>
</div>


<div id="commentsBar">
<div class="fb-comments" data-href="https://theinternet.io/pages/Sure-why-not.html" data-numposts="6" data-colorscheme="light"></div>
</div>';
$subst = '<div id="disqus_thread"></div><script>/***  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION     BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.*  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT:     https://disqus.com/admin/universalcode/#configuration-variables*//*var disqus_config = function () {this.page.url = PAGE_URL;  // Replace PAGE_URL with your page\'s canonical URL variablethis.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page\'s unique identifier variable};*/(function() { // DON\'T EDIT BELOW THIS LINEvar d = document, s = d.createElement(\'script\');s.src = \'https://EXAMPLE.disqus.com/embed.js\';s.setAttribute(\'data-timestamp\', +new Date());(d.head || d.body).appendChild(s);})();</script><noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>';

echo preg_replace($re, $subst, $str);

演示


推荐阅读