单独的图片数据删除清理很方便,使用unlink()
函数就可以了。但如果想要删除清理编辑器中图文混合中的图片,要怎么办呢?这时候可以使用正则匹配提取出是本站的图片数据进行删除,不多说,直接上代码,可根据项目情况自己更改调整。
/**
* 删除编辑器内容中上传的图片数据
*
* @param string $content 编辑器图文内容
*
* @author qinglin
*/
function remove_content_img($content)
{
//匹配并删除图片
$imgreg = "/<img.*src=\"([^\"]+)\"/U";
$matches = [];
preg_match_all($imgreg, $content, $matches);
foreach ($matches[1] as $img_url) {
$web_root = 'http://' . $_SERVER['HTTP_HOST'] . '/';
$filepath = str_replace($web_root, '', $img_url);
if ($filepath == $img_url) $filepath = substr($img_url, 1);
@unlink($filepath);
$filedir = dirname($filepath);
$files = scandir($filedir);
if (count($files) <= 2) @rmdir($filedir);//如果只剩下./和../,就删除文件夹
}
unset($matches);
}