我在理解问题和第一个脚本时犯了一个错误。
此脚本扫描日期目录中的文件(我假设日期目录只包含所需格式的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>
哇,你几乎完全钉它。没想到能得到如此完整的答复,非常感谢!唯一的问题是
标签中的一些标签在其中具有奇怪的属性:。是否有任何简单的修改可以使它在之后附加'origDate',而不是试图只替换? – StrangeBiscuit 2014-10-21 21:53:48@StrangeBiscuit,是的(或我认为)。让我将str_replace修改为reg表达式函数。 – Charles 2014-10-22 12:14:35
@StrangeBiscuit,我已经修改了正则表达式的解决方案,它应该捕获body元素标签中的所有内容。我已经用预期的输出测试了这个,但是让我知道你是否有任何问题。 – Charles 2014-10-22 12:33:26