後台編輯新聞時,使用者可能刪除、新增或保留圖片。需比對「舊內容」與「新內容」的圖片集合,刪除不再被引用的舊圖檔。
$old_contents 解析所有圖片檔名 → 陣列 $oldPic$content 解析所有圖片檔名 → 陣列 $nowPic$intersectPic = array_intersect($nowPic, $oldPic) → 仍被引用的圖片$oldPic,若不在交集中 → unlink() 刪除實體檔案<?php
// 1. 解析舊內容圖片
$oldPic = [];
preg_match_all('/<IMG(.*?)src="(.*?)">/i', $old_contents, $match);
if (!empty($match[2])) {
foreach ($match[2] as $val) {
$oldPic[] = basename($val);
}
}
// 2. 解析新內容圖片
$nowPic = [];
preg_match_all('/<IMG(.*?)src="(.*?)">/i', $content, $testpic);
if (!empty($testpic[2])) {
foreach ($testpic[2] as $val) {
$nowPic[] = basename($val);
}
}
// 3. 計算交集(保留的圖片)
$intersectPic = array_intersect($nowPic, $oldPic);
// 4. 刪除不在交集中的舊圖片
foreach ($oldPic as $val) {
if (!in_array($val, $intersectPic)) {
$delPath = "圖片路徑/" . $val; // 實際專案請用絕對路徑常數
if (file_exists($delPath)) {
unlink($delPath);
}
}
}
/<IMG(.*?)src="(.*?)">/i
i:不區分大小寫(匹配 <img>、<IMG>)(.*?):非貪婪匹配屬性,確保正確捕獲 srcsrc 屬性值,再用 basename() 取純檔名/<IMG(.*?)src=([\"'])(.*?)\2>/ideleted_at,定期清理任務再真正 unlink,防誤刪可恢復正則解析 HTML 屬於「脆弱解析」,大型內容建議改用 DOMDocument 或 DOMXPath 解析,雖稍慢但極大幅度降低誤匹配風險。