ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
#### PHP操作html ``` function replace_material_url($html) { try { // 使用DOM解析器解析HTML $dom = new DOMDocument(); $dom->preserveWhiteSpace = false; $dom->formatOutput = true; $dom->encoding = 'UTF-8'; libxml_use_internal_errors(true); $dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'), LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED); libxml_clear_errors(); // 获取所有a标签 $a_tags = $dom->getElementsByTagName('a'); // 遍历所有a标签并替换href属性值 $isEdit = false; foreach ($a_tags as $a_tag) { $href = $a_tag->getAttribute('href'); // 使用正则表达式匹配值为.html结尾的href属性值 if (preg_match('/\.html$/', $href)) { $itemid = pathinfo($href)['filename']; if (is_numeric($itemid)) { $new_href = 'www.baidu.com' $a_tag->setAttribute('href', $new_href); $isEdit = true; } } } // 获取替换后的HTML代码 if ($isEdit) { $newhtml = trim($dom->saveHTML()); // 去掉多余的 \n return html_entity_decode($newhtml, ENT_QUOTES | ENT_HTML5, 'UTF-8'); } } catch (\Throwable $e) { } return $html; } ``` #### 提示 ~~~ DOMDocument 只支持html4 ,html5标签处理会出错,所以使用了抑制错误 libxml_use_internal_errors(true); libxml_clear_errors(); ~~~