我在理解問題和第一個腳本時犯了一個錯誤。
此腳本掃描日期目錄中的文件(我假設日期目錄只包含所需格式的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