循环遍历html文件,获取文件名并插入到每个文件中

问题描述 投票:0回答:1

我正在将网站迁移到 Wordpress...旧网站使用定制的发布系统,其中 PHP 模板调用每个帖子的单独静态 HTML 文件。有相当多的帖子需要迁移(超过 1000 个)。

我正在使用一个插件,可以导入 HTML 文件并将每个文件转换为 Wordpress 帖子,但正确设置每个帖子的原始日期非常重要。方便的是,该插件允许我从每个文件中的 HTML 标签中选择每个帖子的日期。

我的问题是日期都在文件名中,而不是文件本身。这些文件均以 yy-mm-dd 命名,但没有破折号,因此它们看起来像:

"130726.htm"
(2013 年 7 月 26 日)
"121025.htm"
(2012 年 10 月 25 日)

所以基本上我需要一种方法来循环访问这些文件的目录,并且对于每个文件 - 获取文件名,添加斜杠,然后将其插入到文件中的

<body>
之后的标签中,例如:
<p class="origDate">13/07/26</p>

我不确定解决这个问题的最佳方法...Python 脚本、Notepad++ 宏、批处理文件或其他任何东西。任何人都可以提供任何帮助/提示/建议吗?他们将不胜感激!

提前致谢!

php html wordpress batch-processing
1个回答
0
投票

我在理解问题和第一个脚本时犯了一个错误。

此脚本扫描日期目录中的文件(我在这里假设日期目录仅包含您所需格式的html文件),然后打开文件并在正文下方插入段落。

日期文件夹的示例内容:

121214.html 121298.html 121299.html

PHP 脚本(脚本放置在与日期文件夹相同的目录中):

<?php
$dir = "dates";
$a = scandir($dir);

$a = array_diff($a, array(".", ".."));



foreach ($a as $value)
{


   $string = file_get_contents("dates/".$value);





   $newstring = substr($value,0,-5);
   $newstring1 = substr($newstring,0,2);
   $newstring2 = substr($newstring,2,2);
   $newstring3 = substr($newstring,4,2);
   $para =  '<p class="origDate">' .$newstring1 . "/" . $newstring2 . "/" . $newstring3 . '</p>' . "<br>";
   $pattern = '/<body[\w\s="-:;]*>/';
   $replacement = '${0}'.$para;
   $newpara = preg_replace($pattern, $replacement, $string);



   $filename ="dates/".$value;
   $file = fopen($filename, "r+");

   fwrite($file, $newpara);
   fclose($file);

}
?>

我这里使用了.html,要使用.htm,修改这一行:

$newstring = substr($value,0,-5);

$newstring = substr($value,0,-4);

之前的 HTML 示例:

<!DOCTYPE html>
<html>

<body marginwidth=0 style="margin-left: 30px;" onclick="myfunction()">

<ul><li>Coffee</li><li>Tea</li></ul>

</body>
</html>

之后的 HTML 示例:

<!DOCTYPE html>
<html>
<body marginwidth=0 style="margin-left: 30px;" onclick="myfunction()"><p class="origDate">12/12/14</p><br>

<ul><li>Coffee</li><li>Tea</li></ul>



</body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.