给字符串中的每个<a>
增加一个download属性
// 准备一串包含DOM需要操作的字符串
$str = '<p style="line-height: 16px;"><img src="http://localhost:8002/js/plugins/ueditor/dialogs/attachment/fileTypeImages/icon_txt.gif"/><a style="font-size:12px; color:#0066cc;" href="http://localhost:8002/uploadfiles/activity_content_file/20210406/202104061105166165.docx?f21" title="Git使用说明.docx">Git使用说明.docx</a></p><p style="line-height: 16px;"><img src="http://localhost:8002/js/plugins/ueditor/dialogs/attachment/fileTypeImages/icon_txt.gif"/><a style="font-size:12px; color:#0066cc;" href="http://localhost:8002/uploadfiles/activity_content_file/20210419/202104191046171056.jpg?f20" title="1.jpg">1.jpg</a></p><p><br/></p>';
// 引入DOM操作类
$doc= new DOMDocument();
// DOM操作前进行转码
$encode_str = mb_convert_encoding($str, 'HTML-ENTITIES', 'UTF-8');
// 载入DOM
$doc->loadHTML($encode_str);
// 获取其中的a标签
$aTag = $doc->getElementsByTagName('a');
// 给a标签设置download属性值
foreach ($aTag as $key => $tag) {
$tag->setAttribute('download',$tag->nodeValue);
}
// 输出处理后的结果,这些字符串是包含html、header等标签的
$result = $doc->saveHTML();
// 这里去掉html、header、body等标签,就得到结果
$content = preg_replace(array("/^\<\!DOCTYPE.*?<html><body>/si","!</body></html>$!si"),"",$result);